Search in sources :

Example 1 with MultiTextEdit

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

the class StubUtility method fixEmptyVariables.

// remove lines for empty variables
private static String fixEmptyVariables(TemplateBuffer buffer, String[] variables) throws MalformedTreeException, BadLocationException {
    IDocument doc = new Document(buffer.getString());
    int nLines = doc.getNumberOfLines();
    MultiTextEdit edit = new MultiTextEdit();
    HashSet<Integer> removedLines = new HashSet<Integer>();
    for (int i = 0; i < variables.length; i++) {
        // look if Javadoc tags have to be added
        TemplateVariable position = findVariable(buffer, variables[i]);
        if (position == null || position.getLength() > 0) {
            continue;
        }
        int[] offsets = position.getOffsets();
        for (int k = 0; k < offsets.length; k++) {
            int line = doc.getLineOfOffset(offsets[k]);
            IRegion lineInfo = doc.getLineInformation(line);
            int offset = lineInfo.getOffset();
            String str = doc.get(offset, lineInfo.getLength());
            if (Strings.containsOnlyWhitespaces(str) && nLines > line + 1 && removedLines.add(new Integer(line))) {
                int nextStart = doc.getLineOffset(line + 1);
                edit.addChild(new DeleteEdit(offset, nextStart - offset));
            }
        }
    }
    edit.apply(doc, 0);
    return doc.get();
}
Also used : TemplateVariable(org.eclipse.jface.text.templates.TemplateVariable) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) DeleteEdit(org.eclipse.text.edits.DeleteEdit) IDocument(org.eclipse.jface.text.IDocument) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) IRegion(org.eclipse.jface.text.IRegion) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 2 with MultiTextEdit

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

the class ExtractMethodRefactoring method createChange.

/* (non-Javadoc)
	 * Method declared in IRefactoring
	 */
@Override
public Change createChange(IProgressMonitor pm) throws CoreException {
    if (fMethodName == null)
        return null;
    //$NON-NLS-1$
    pm.beginTask("", 2);
    try {
        fAnalyzer.aboutToCreateChange();
        BodyDeclaration declaration = fAnalyzer.getEnclosingBodyDeclaration();
        fRewriter = ASTRewrite.create(declaration.getAST());
        final CompilationUnitChange result = new CompilationUnitChange(RefactoringCoreMessages.ExtractMethodRefactoring_change_name, fCUnit);
        result.setSaveMode(TextFileChange.KEEP_SAVE_STATE);
        result.setDescriptor(new RefactoringChangeDescriptor(getRefactoringDescriptor()));
        MultiTextEdit root = new MultiTextEdit();
        result.setEdit(root);
        ASTNode[] selectedNodes = fAnalyzer.getSelectedNodes();
        fRewriter.setTargetSourceRangeComputer(new SelectionAwareSourceRangeComputer(selectedNodes, fCUnit.getBuffer(), fSelectionStart, fSelectionLength));
        TextEditGroup substituteDesc = new TextEditGroup(Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_substitute_with_call, BasicElementLabels.getJavaElementName(fMethodName)));
        result.addTextEditGroup(substituteDesc);
        MethodDeclaration mm = createNewMethod(selectedNodes, fCUnit.findRecommendedLineSeparator(), substituteDesc);
        if (fLinkedProposalModel != null) {
            LinkedProposalPositionGroup typeGroup = fLinkedProposalModel.getPositionGroup(KEY_TYPE, true);
            typeGroup.addPosition(fRewriter.track(mm.getReturnType2()), false);
            ITypeBinding typeBinding = fAnalyzer.getReturnTypeBinding();
            if (typeBinding != null) {
                ITypeBinding[] relaxingTypes = ASTResolving.getNarrowingTypes(fAST, typeBinding);
                for (int i = 0; i < relaxingTypes.length; i++) {
                    typeGroup.addProposal(relaxingTypes[i], fCUnit, relaxingTypes.length - i);
                }
            }
            LinkedProposalPositionGroup nameGroup = fLinkedProposalModel.getPositionGroup(KEY_NAME, true);
            nameGroup.addPosition(fRewriter.track(mm.getName()), false);
            ModifierCorrectionSubProcessor.installLinkedVisibilityProposals(fLinkedProposalModel, fRewriter, mm.modifiers(), false);
        }
        TextEditGroup insertDesc = new TextEditGroup(Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_add_method, BasicElementLabels.getJavaElementName(fMethodName)));
        result.addTextEditGroup(insertDesc);
        if (fDestination == ASTResolving.findParentType(declaration.getParent())) {
            ChildListPropertyDescriptor desc = (ChildListPropertyDescriptor) declaration.getLocationInParent();
            ListRewrite container = fRewriter.getListRewrite(declaration.getParent(), desc);
            container.insertAfter(mm, declaration, insertDesc);
        } else {
            BodyDeclarationRewrite container = BodyDeclarationRewrite.create(fRewriter, fDestination);
            container.insert(mm, insertDesc);
        }
        replaceDuplicates(result, mm.getModifiers());
        replaceBranches(result);
        if (fImportRewriter.hasRecordedChanges()) {
            TextEdit edit = fImportRewriter.rewriteImports(null);
            root.addChild(edit);
            result.addTextEditGroup(new TextEditGroup(RefactoringCoreMessages.ExtractMethodRefactoring_organize_imports, new TextEdit[] { edit }));
        }
        root.addChild(fRewriter.rewriteAST());
        return result;
    } finally {
        pm.done();
    }
}
Also used : SelectionAwareSourceRangeComputer(org.eclipse.jdt.internal.corext.refactoring.util.SelectionAwareSourceRangeComputer) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) RefactoringChangeDescriptor(org.eclipse.ltk.core.refactoring.RefactoringChangeDescriptor) ChildListPropertyDescriptor(org.eclipse.jdt.core.dom.ChildListPropertyDescriptor) BodyDeclarationRewrite(org.eclipse.jdt.internal.corext.dom.BodyDeclarationRewrite) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) TextEditGroup(org.eclipse.text.edits.TextEditGroup) LinkedProposalPositionGroup(org.eclipse.jdt.internal.corext.fix.LinkedProposalPositionGroup) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) CompilationUnitChange(org.eclipse.jdt.core.refactoring.CompilationUnitChange)

Example 3 with MultiTextEdit

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

the class IntroduceFactoryRefactoring method addAllChangesFor.

/**
	 * Add all changes necessary on the <code>ICompilationUnit</code> in the given
	 * <code>SearchResultGroup</code> to implement the refactoring transformation
	 * to the given <code>CompilationUnitChange</code>.
	 * @param rg the <code>SearchResultGroup</code> for which changes should be created
	 * @param unitHandle
	 * @param unitChange the CompilationUnitChange object for the compilation unit in question
	 * @return <code>true</code> iff a change has been added
	 * @throws CoreException
	 */
private boolean addAllChangesFor(SearchResultGroup rg, ICompilationUnit unitHandle, CompilationUnitChange unitChange) throws CoreException {
    //		ICompilationUnit	unitHandle= rg.getCompilationUnit();
    Assert.isTrue(rg == null || rg.getCompilationUnit() == unitHandle);
    CompilationUnit unit = getASTFor(unitHandle);
    ASTRewrite unitRewriter = ASTRewrite.create(unit.getAST());
    MultiTextEdit root = new MultiTextEdit();
    boolean someChange = false;
    unitChange.setEdit(root);
    fImportRewriter = StubUtility.createImportRewrite(unit, true);
    // First create the factory method
    if (unitHandle.equals(fFactoryUnitHandle)) {
        TextEditGroup factoryGD = new TextEditGroup(RefactoringCoreMessages.IntroduceFactory_addFactoryMethod);
        createFactoryChange(unitRewriter, unit, factoryGD);
        unitChange.addTextEditGroup(factoryGD);
        someChange = true;
    }
    // Now rewrite all the constructor calls to use the factory method
    if (rg != null)
        if (replaceConstructorCalls(rg, unit, unitRewriter, unitChange))
            someChange = true;
    // Finally, make the constructor private, if requested.
    if (shouldProtectConstructor() && isConstructorUnit(unitHandle)) {
        TextEditGroup declGD = new TextEditGroup(RefactoringCoreMessages.IntroduceFactory_protectConstructor);
        if (protectConstructor(unit, unitRewriter, declGD)) {
            unitChange.addTextEditGroup(declGD);
            someChange = true;
        }
    }
    if (someChange) {
        root.addChild(unitRewriter.rewriteAST());
        root.addChild(fImportRewriter.rewriteImports(null));
    }
    return someChange;
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) TextEditGroup(org.eclipse.text.edits.TextEditGroup) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit)

Example 4 with MultiTextEdit

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

the class InlineMethodRefactoring method checkFinalConditions.

@Override
public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
    //$NON-NLS-1$
    pm.beginTask("", 20);
    fChangeManager = new TextChangeManager();
    RefactoringStatus result = new RefactoringStatus();
    fSourceProvider.initialize();
    fTargetProvider.initialize();
    pm.setTaskName(RefactoringCoreMessages.InlineMethodRefactoring_searching);
    RefactoringStatus searchStatus = new RefactoringStatus();
    String binaryRefsDescription = Messages.format(RefactoringCoreMessages.ReferencesInBinaryContext_ref_in_binaries_description, BasicElementLabels.getJavaElementName(fSourceProvider.getMethodName()));
    ReferencesInBinaryContext binaryRefs = new ReferencesInBinaryContext(binaryRefsDescription);
    ICompilationUnit[] units = fTargetProvider.getAffectedCompilationUnits(searchStatus, binaryRefs, new SubProgressMonitor(pm, 1));
    binaryRefs.addErrorIfNecessary(searchStatus);
    if (searchStatus.hasFatalError()) {
        result.merge(searchStatus);
        return result;
    }
    IFile[] filesToBeModified = getFilesToBeModified(units);
    result.merge(Checks.validateModifiesFiles(filesToBeModified, getValidationContext()));
    if (result.hasFatalError())
        return result;
    result.merge(ResourceChangeChecker.checkFilesToBeChanged(filesToBeModified, new SubProgressMonitor(pm, 1)));
    checkOverridden(result, new SubProgressMonitor(pm, 4));
    IProgressMonitor sub = new SubProgressMonitor(pm, 15);
    //$NON-NLS-1$
    sub.beginTask("", units.length * 3);
    for (int c = 0; c < units.length; c++) {
        ICompilationUnit unit = units[c];
        sub.subTask(Messages.format(RefactoringCoreMessages.InlineMethodRefactoring_processing, BasicElementLabels.getFileName(unit)));
        CallInliner inliner = null;
        try {
            boolean added = false;
            MultiTextEdit root = new MultiTextEdit();
            CompilationUnitChange change = (CompilationUnitChange) fChangeManager.get(unit);
            change.setEdit(root);
            BodyDeclaration[] bodies = fTargetProvider.getAffectedBodyDeclarations(unit, new SubProgressMonitor(pm, 1));
            if (bodies.length == 0)
                continue;
            inliner = new CallInliner(unit, (CompilationUnit) bodies[0].getRoot(), fSourceProvider);
            for (int b = 0; b < bodies.length; b++) {
                BodyDeclaration body = bodies[b];
                inliner.initialize(body);
                RefactoringStatus nestedInvocations = new RefactoringStatus();
                ASTNode[] invocations = removeNestedCalls(nestedInvocations, unit, fTargetProvider.getInvocations(body, new SubProgressMonitor(sub, 2)));
                for (int i = 0; i < invocations.length; i++) {
                    ASTNode invocation = invocations[i];
                    result.merge(inliner.initialize(invocation, fTargetProvider.getStatusSeverity()));
                    if (result.hasFatalError())
                        break;
                    if (result.getSeverity() < fTargetProvider.getStatusSeverity()) {
                        added = true;
                        TextEditGroup group = new TextEditGroup(RefactoringCoreMessages.InlineMethodRefactoring_edit_inline);
                        change.addTextEditGroup(group);
                        result.merge(inliner.perform(group));
                    } else {
                        fDeleteSource = false;
                    }
                }
                // to generate the modifications.
                if (!nestedInvocations.isOK()) {
                    result.merge(nestedInvocations);
                    fDeleteSource = false;
                }
            }
            if (!added) {
                fChangeManager.remove(unit);
            } else {
                root.addChild(inliner.getModifications());
                ImportRewrite rewrite = inliner.getImportEdit();
                if (rewrite.hasRecordedChanges()) {
                    TextEdit edit = rewrite.rewriteImports(null);
                    if (edit instanceof MultiTextEdit ? ((MultiTextEdit) edit).getChildrenSize() > 0 : true) {
                        root.addChild(edit);
                        change.addTextEditGroup(new TextEditGroup(RefactoringCoreMessages.InlineMethodRefactoring_edit_import, new TextEdit[] { edit }));
                    }
                }
            }
        } finally {
            if (inliner != null)
                inliner.dispose();
        }
        sub.worked(1);
        if (sub.isCanceled())
            throw new OperationCanceledException();
    }
    result.merge(searchStatus);
    sub.done();
    pm.done();
    return result;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IFile(org.eclipse.core.resources.IFile) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) ReferencesInBinaryContext(org.eclipse.jdt.internal.corext.refactoring.base.ReferencesInBinaryContext) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) ASTNode(org.eclipse.jdt.core.dom.ASTNode) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) TextEditGroup(org.eclipse.text.edits.TextEditGroup) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextChangeManager(org.eclipse.jdt.internal.corext.refactoring.util.TextChangeManager) CompilationUnitChange(org.eclipse.jdt.core.refactoring.CompilationUnitChange)

Example 5 with MultiTextEdit

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

the class TextChange method createTextEditProcessor.

private TextEditProcessor createTextEditProcessor(IDocument document, int flags, TextEditBasedChangeGroup[] changes) {
    if (fEdit == null)
        return new TextEditProcessor(document, new MultiTextEdit(0, 0), flags);
    List includes = new ArrayList(0);
    for (int c = 0; c < changes.length; c++) {
        TextEditBasedChangeGroup change = changes[c];
        Assert.isTrue(change.getTextEditChange() == this);
        if (change.isEnabled()) {
            includes.addAll(Arrays.asList(change.getTextEditGroup().getTextEdits()));
        }
    }
    fCopier = new TextEditCopier(fEdit);
    TextEdit copiedEdit = fCopier.perform();
    boolean keep = getKeepPreviewEdits();
    if (keep)
        flags = flags | TextEdit.UPDATE_REGIONS;
    LocalTextEditProcessor result = new LocalTextEditProcessor(document, copiedEdit, flags);
    result.setIncludes(mapEdits((TextEdit[]) includes.toArray(new TextEdit[includes.size()]), fCopier));
    if (!keep)
        fCopier = null;
    return result;
}
Also used : TextEditCopier(org.eclipse.text.edits.TextEditCopier) TextEditProcessor(org.eclipse.text.edits.TextEditProcessor) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit)

Aggregations

MultiTextEdit (org.eclipse.text.edits.MultiTextEdit)27 TextEdit (org.eclipse.text.edits.TextEdit)19 CompilationUnitChange (org.eclipse.jdt.core.refactoring.CompilationUnitChange)9 TextEditGroup (org.eclipse.text.edits.TextEditGroup)9 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)6 ASTNode (org.eclipse.jdt.core.dom.ASTNode)5 Document (org.eclipse.jface.text.Document)5 IDocument (org.eclipse.jface.text.IDocument)5 HashSet (java.util.HashSet)4 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)4 OperationCanceledException (org.eclipse.core.runtime.OperationCanceledException)4 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)4 IRegion (org.eclipse.jface.text.IRegion)4 TextChange (org.eclipse.ltk.core.refactoring.TextChange)4 TextEditProcessor (org.eclipse.text.edits.TextEditProcessor)4 ArrayList (java.util.ArrayList)3 List (java.util.List)3 IFile (org.eclipse.core.resources.IFile)3 IProgressMonitor (org.eclipse.core.runtime.IProgressMonitor)3 SubProgressMonitor (org.eclipse.core.runtime.SubProgressMonitor)3