Search in sources :

Example 91 with TextEdit

use of org.eclipse.text.edits.TextEdit in project whole by wholeplatform.

the class JDTUtils method asFormattedDocument.

@SuppressWarnings("unchecked")
public static Document asFormattedDocument(ASTNode astNode, int kind) {
    String source = asString(astNode);
    Document document = new Document(source);
    Map<String, String> options = JavaCore.getOptions();
    options.put(JavaCore.COMPILER_SOURCE, "1.5");
    options.put(JavaCore.COMPILER_COMPLIANCE, "1.5");
    options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, "1.5");
    CodeFormatter formatter = ToolFactory.createCodeFormatter(options);
    TextEdit textEdit = formatter.format(kind, source, 0, source.length(), 0, null);
    try {
        textEdit.apply(document);
    } catch (Exception e) {
        throw new IllegalArgumentException();
    }
    return document;
}
Also used : CodeFormatter(org.eclipse.jdt.core.formatter.CodeFormatter) TextEdit(org.eclipse.text.edits.TextEdit) Document(org.eclipse.jface.text.Document) CoreException(org.eclipse.core.runtime.CoreException) JavaModelException(org.eclipse.jdt.core.JavaModelException) MalformedURLException(java.net.MalformedURLException)

Example 92 with TextEdit

use of org.eclipse.text.edits.TextEdit in project titan.EclipsePlug-ins by eclipse.

the class ChangeCreator method createTextEdit.

private TextEdit[] createTextEdit(final IFile toVisit, final String fileContent, final Edit e, final Map<Edit, InsertEdit> editsDone) {
    // check for multi-declaration statement
    if (e.declSt.isMultiDeclaration()) {
        final Location cutLoc = calculateMultiDeclarationCutLoc(fileContent, e.declSt);
        final String moveContent = calculateMultiDeclarationMoveContent(fileContent, e.declSt);
        // remove stmt from multi-declaration
        e.declSt.removeFromMultiDeclaration();
        // create remove edit
        final int cutLen = cutLoc.getEndOffset() - cutLoc.getOffset();
        final TextEdit cut = new DeleteEdit(cutLoc.getOffset(), cutLen);
        // create insert edit
        InsertEdit insert = null;
        if (!e.isRemoveEdit()) {
            // update insert location if the insertionPoint stmt was moved
            int insertOffset = ((ILocateableNode) e.insertionPoint.getAstNode()).getLocation().getOffset();
            for (Map.Entry<Edit, InsertEdit> ed : editsDone.entrySet()) {
                if (ed.getKey().declSt.equals(e.insertionPoint)) {
                    insertOffset = ed.getValue().getOffset();
                    break;
                }
            }
            // 
            insertOffset = findLineBeginningOffset(fileContent, insertOffset);
            insert = new InsertEdit(insertOffset, moveContent);
            editsDone.put(e, insert);
        }
        if (insert != null) {
            return new TextEdit[] { insert, cut };
        }
        return new TextEdit[] { cut };
    } else {
        // 
        final Location cutLoc = findStatementLocation(fileContent, ((ILocateableNode) e.declSt.getAstNode()).getLocation(), true);
        InsertEdit insert = null;
        if (!e.isRemoveEdit()) {
            final Location copyLoc = findStatementLocation(fileContent, ((ILocateableNode) e.declSt.getAstNode()).getLocation(), false);
            // update insert location if the insertionPoint stmt was moved
            final Location insPLoc = ((ILocateableNode) e.insertionPoint.getAstNode()).getLocation();
            int insertOffset = insPLoc.getOffset();
            for (Map.Entry<Edit, InsertEdit> ed : editsDone.entrySet()) {
                if (ed.getKey().declSt.equals(e.insertionPoint)) {
                    insertOffset = ed.getValue().getOffset();
                    break;
                }
            }
            // 
            final int prefixStartOffset = findLineBeginningOffset(fileContent, insertOffset);
            final String insertText = fileContent.substring(copyLoc.getOffset(), copyLoc.getEndOffset()) + "\n";
            String insertPrefix = fileContent.substring(prefixStartOffset, insertOffset);
            // if prefix is not whitespace only, do not use the prefix
            if (!insertPrefix.trim().equals("")) {
                insertPrefix = "";
            }
            insert = new InsertEdit(prefixStartOffset, insertPrefix + insertText);
            editsDone.put(e, insert);
        }
        final int cutLen = cutLoc.getEndOffset() - cutLoc.getOffset();
        final TextEdit cut = new DeleteEdit(cutLoc.getOffset(), cutLen);
        // System.err.println("DeleteEdit: " + fileContent.substring(cutLoc.getOffset(), cutLoc.getEndOffset()));
        if (insert != null) {
            return new TextEdit[] { insert, cut };
        }
        return new TextEdit[] { cut };
    }
}
Also used : InsertEdit(org.eclipse.text.edits.InsertEdit) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) ILocateableNode(org.eclipse.titan.designer.AST.ILocateableNode) Edit(org.eclipse.titanium.refactoring.scope.nodes.Edit) InsertEdit(org.eclipse.text.edits.InsertEdit) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) DeleteEdit(org.eclipse.text.edits.DeleteEdit) DeleteEdit(org.eclipse.text.edits.DeleteEdit) Map(java.util.Map) HashMap(java.util.HashMap) Location(org.eclipse.titan.designer.AST.Location)

Example 93 with TextEdit

use of org.eclipse.text.edits.TextEdit in project titan.EclipsePlug-ins by eclipse.

the class ChangeCreator method createFileChange.

/**
 * Creates the {@link #change} object, which contains all the inserted and edited texts
 * in the selected resources.
 */
private Change createFileChange(final IFile toVisit) {
    if (toVisit == null) {
        return null;
    }
    final ProjectSourceParser sourceParser = GlobalParser.getProjectSourceParser(toVisit.getProject());
    final Module module = sourceParser.containedModule(toVisit);
    if (module == null) {
        return null;
    }
    // 
    // collect functions
    Set<Definition> funcs;
    final FunctionCollector vis = new FunctionCollector();
    if (defSelection == null) {
        module.accept(vis);
        funcs = vis.getResult();
    } else {
        if (defSelection instanceof Def_Function || defSelection instanceof Def_Testcase) {
            // TODO any other possibilities for the type of 'defSelection'?
            funcs = new HashSet<Definition>();
            funcs.add(defSelection);
        } else {
            ErrorReporter.logError("Variable scope reduction called for " + defSelection.getIdentifier().getDisplayName() + ", but it is only supported for functions and testcases. ");
            return null;
        }
    }
    // create edits
    final List<Edit> allEdits = new ArrayList<Edit>();
    for (Definition def : funcs) {
        final List<Edit> edits = analyzeFunction(def);
        if (edits == null) {
            continue;
        }
        allEdits.addAll(edits);
    }
    if (allEdits.isEmpty()) {
        return null;
    }
    final String fileContents = loadFileContent(toVisit);
    // create text edits
    // 
    final TextFileChange tfc = new TextFileChange(toVisit.getName(), toVisit);
    final MultiTextEdit rootEdit = new MultiTextEdit();
    tfc.setEdit(rootEdit);
    // TODO this is an O(n^2) algorithm
    // merge overlapping DeleteEdits
    // used, when removing all parts of a multi-declaration statement:
    // the DeleteEdit for removing the last part covers all the DeleteEdits for the other parts
    // WARNING merging edits might make debugging more difficult, since the overlapping edit errors are avoided
    final List<TextEdit> allTes = new LinkedList<TextEdit>();
    // collect processed (insert) edits with their created insert edit
    final Map<Edit, InsertEdit> editsDone = new HashMap<Edit, InsertEdit>();
    for (Edit e : allEdits) {
        final TextEdit[] tes = createTextEdit(toVisit, fileContents, e, editsDone);
        for (TextEdit te : tes) {
            if (!(te instanceof DeleteEdit)) {
                allTes.add(te);
                // System.err.println("$ nonde added: " + te.getOffset() + "-" + te.getExclusiveEnd());
                continue;
            }
            DeleteEdit dte = (DeleteEdit) te;
            final ListIterator<TextEdit> it = allTes.listIterator();
            while (it.hasNext()) {
                final TextEdit currTe = it.next();
                if (!(currTe instanceof DeleteEdit)) {
                    continue;
                }
                final DeleteEdit currDte = (DeleteEdit) currTe;
                // if the new edit (dte) overlaps currDte, merge them
                if (doesDeleteEditsOverlap(dte, currDte)) {
                    // System.err.println("$ de removed: " + currDte.getOffset() + "-" + currDte.getExclusiveEnd());
                    it.remove();
                    dte = mergeDeleteEdits(dte, currDte);
                // System.err.println("$ merged des: " + dte.getOffset() + "-" + dte.getExclusiveEnd());
                }
            }
            // System.err.println("$ de added: " + dte.getOffset() + "-" + dte.getExclusiveEnd());
            allTes.add(dte);
        }
    }
    Collections.reverse(allTes);
    for (TextEdit te : allTes) {
        rootEdit.addChild(te);
    }
    return tfc;
}
Also used : InsertEdit(org.eclipse.text.edits.InsertEdit) Def_Testcase(org.eclipse.titan.designer.AST.TTCN3.definitions.Def_Testcase) HashMap(java.util.HashMap) Definition(org.eclipse.titan.designer.AST.TTCN3.definitions.Definition) ArrayList(java.util.ArrayList) Edit(org.eclipse.titanium.refactoring.scope.nodes.Edit) InsertEdit(org.eclipse.text.edits.InsertEdit) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) DeleteEdit(org.eclipse.text.edits.DeleteEdit) TextFileChange(org.eclipse.ltk.core.refactoring.TextFileChange) DeleteEdit(org.eclipse.text.edits.DeleteEdit) ProjectSourceParser(org.eclipse.titan.designer.parsers.ProjectSourceParser) Def_Function(org.eclipse.titan.designer.AST.TTCN3.definitions.Def_Function) LinkedList(java.util.LinkedList) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) Module(org.eclipse.titan.designer.AST.Module) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit)

Example 94 with TextEdit

use of org.eclipse.text.edits.TextEdit in project ch.hsr.ifs.cdttesting by IFS-HSR.

the class TestProjectHolder method formatFileAsync.

@Override
public ProjectHolderJob formatFileAsync(IPath path) {
    return ProjectHolderJob.create("Formatting project " + projectName, ITestProjectHolder.FORMATT_FILE_JOB_FAMILY, mon -> {
        if (!formattedDocuments.contains(path)) {
            final IDocument doc = getDocument(getFile(path));
            final Map<String, Object> options = new HashMap<>(cProject.getOptions(true));
            try {
                final ITranslationUnit tu = CoreModelUtil.findTranslationUnitForLocation(path, cProject);
                options.put(DefaultCodeFormatterConstants.FORMATTER_TRANSLATION_UNIT, tu);
                final CodeFormatter formatter = ToolFactory.createCodeFormatter(options);
                final TextEdit te = formatter.format(CodeFormatter.K_TRANSLATION_UNIT, path.toOSString(), 0, doc.getLength(), 0, NL);
                te.apply(doc);
                formattedDocuments.add(path);
            } catch (CModelException | MalformedTreeException | BadLocationException e) {
                e.printStackTrace();
            }
        }
    });
}
Also used : CodeFormatter(org.eclipse.cdt.core.formatter.CodeFormatter) HashMap(java.util.HashMap) TextEdit(org.eclipse.text.edits.TextEdit) CModelException(org.eclipse.cdt.core.model.CModelException) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) IDocument(org.eclipse.jface.text.IDocument) ITranslationUnit(org.eclipse.cdt.core.model.ITranslationUnit) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 95 with TextEdit

use of org.eclipse.text.edits.TextEdit in project webtools.sourceediting by eclipse.

the class JSPTranslationUtil method translateTextEdit.

public TextEdit translateTextEdit(TextEdit textEdit) {
    TextEdit translatedTextEdit = null;
    int javaOffset = textEdit.getOffset();
    int jspOffset = getTranslation().getJspOffset(textEdit.getOffset());
    int length = textEdit.getLength();
    if (textEdit instanceof MultiTextEdit) {
        translatedTextEdit = new MultiTextEdit();
        TextEdit[] children = ((MultiTextEdit) textEdit).getChildren();
        for (int i = 0; i < children.length; i++) {
            TextEdit translatedChildTextEdit = translateTextEdit(children[i]);
            if (translatedChildTextEdit != null)
                ((MultiTextEdit) translatedTextEdit).addChild(translatedChildTextEdit);
        }
    } else if (textEdit instanceof ReplaceEdit) {
        if (jspOffset == -1)
            return null;
        if (!getTranslation().javaSpansMultipleJspPartitions(javaOffset, length))
            translatedTextEdit = new ReplaceEdit(jspOffset, length, ((ReplaceEdit) textEdit).getText());
    } else if (textEdit instanceof InsertEdit) {
        translatedTextEdit = new InsertEdit(jspOffset, ((InsertEdit) textEdit).getText());
    } else if (textEdit instanceof DeleteEdit) {
        translatedTextEdit = new DeleteEdit(jspOffset, length);
        TextEdit[] children = ((DeleteEdit) textEdit).getChildren();
        for (int i = 0; i < children.length; i++) {
            TextEdit translatedChildTextEdit = translateTextEdit(children[i]);
            if (translatedChildTextEdit != null)
                ((DeleteEdit) translatedTextEdit).addChild(translatedChildTextEdit);
        }
    } else if (textEdit instanceof CopySourceEdit) {
        translatedTextEdit = new CopySourceEdit(jspOffset, length);
        ((CopySourceEdit) translatedTextEdit).setTargetEdit(((CopySourceEdit) textEdit).getTargetEdit());
        ((CopySourceEdit) translatedTextEdit).setSourceModifier(((CopySourceEdit) textEdit).getSourceModifier());
    } else if (textEdit instanceof CopyTargetEdit) {
        translatedTextEdit = new CopyTargetEdit(jspOffset);
        ((CopyTargetEdit) textEdit).getSourceEdit().setTargetEdit((CopyTargetEdit) translatedTextEdit);
    } else if (textEdit instanceof MoveSourceEdit) {
        translatedTextEdit = new MoveSourceEdit(jspOffset, length);
        ((MoveSourceEdit) translatedTextEdit).setTargetEdit(((MoveSourceEdit) textEdit).getTargetEdit());
    } else if (textEdit instanceof MoveTargetEdit) {
        translatedTextEdit = new MoveTargetEdit(jspOffset);
        ((MoveTargetEdit) textEdit).getSourceEdit().setTargetEdit((MoveTargetEdit) translatedTextEdit);
    } else {
        // $NON-NLS-1$
        System.out.println("Need to translate " + textEdit);
    }
    return translatedTextEdit;
}
Also used : InsertEdit(org.eclipse.text.edits.InsertEdit) CopySourceEdit(org.eclipse.text.edits.CopySourceEdit) MoveTargetEdit(org.eclipse.text.edits.MoveTargetEdit) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit) CopyTargetEdit(org.eclipse.text.edits.CopyTargetEdit) MoveSourceEdit(org.eclipse.text.edits.MoveSourceEdit) DeleteEdit(org.eclipse.text.edits.DeleteEdit) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit)

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