Search in sources :

Example 76 with TextEdit

use of org.eclipse.text.edits.TextEdit in project eclipse.jdt.ls by eclipse.

the class ASTRewriteCorrectionProposal method addEdits.

@Override
protected void addEdits(IDocument document, TextEdit editRoot) throws CoreException {
    super.addEdits(document, editRoot);
    ASTRewrite rewrite = getRewrite();
    if (rewrite != null) {
        try {
            TextEdit edit = rewrite.rewriteAST();
            editRoot.addChild(edit);
        } catch (IllegalArgumentException e) {
            throw new CoreException(StatusFactory.newErrorStatus("Invalid AST rewriter", e));
        }
    }
    if (fImportRewrite != null) {
        editRoot.addChild(fImportRewrite.rewriteImports(new NullProgressMonitor()));
    }
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) CoreException(org.eclipse.core.runtime.CoreException) TextEdit(org.eclipse.text.edits.TextEdit) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite)

Example 77 with TextEdit

use of org.eclipse.text.edits.TextEdit in project eclipse.jdt.ls by eclipse.

the class DocumentLifeCycleHandler method handleChanged.

public void handleChanged(DidChangeTextDocumentParams params) {
    ICompilationUnit unit = JDTUtils.resolveCompilationUnit(params.getTextDocument().getUri());
    if (unit == null || !unit.isWorkingCopy() || params.getContentChanges().isEmpty()) {
        return;
    }
    try {
        if (unit.equals(sharedASTProvider.getActiveJavaElement())) {
            sharedASTProvider.disposeAST();
        }
        List<TextDocumentContentChangeEvent> contentChanges = params.getContentChanges();
        for (TextDocumentContentChangeEvent changeEvent : contentChanges) {
            Range range = changeEvent.getRange();
            int length;
            if (range != null) {
                length = changeEvent.getRangeLength().intValue();
            } else {
                // range is optional and if not given, the whole file content is replaced
                length = unit.getSource().length();
                range = JDTUtils.toRange(unit, 0, length);
            }
            int startOffset = JsonRpcHelpers.toOffset(unit.getBuffer(), range.getStart().getLine(), range.getStart().getCharacter());
            TextEdit edit = null;
            String text = changeEvent.getText();
            if (length == 0) {
                edit = new InsertEdit(startOffset, text);
            } else if (text.isEmpty()) {
                edit = new DeleteEdit(startOffset, length);
            } else {
                edit = new ReplaceEdit(startOffset, length, text);
            }
            IDocument document = JsonRpcHelpers.toDocument(unit.getBuffer());
            edit.apply(document, TextEdit.NONE);
        }
        triggerValidation(unit);
    } catch (JavaModelException | MalformedTreeException | BadLocationException e) {
        JavaLanguageServerPlugin.logException("Error while handling document change", e);
    }
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) InsertEdit(org.eclipse.text.edits.InsertEdit) JavaModelException(org.eclipse.jdt.core.JavaModelException) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) Range(org.eclipse.lsp4j.Range) DeleteEdit(org.eclipse.text.edits.DeleteEdit) TextDocumentContentChangeEvent(org.eclipse.lsp4j.TextDocumentContentChangeEvent) TextEdit(org.eclipse.text.edits.TextEdit) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 78 with TextEdit

use of org.eclipse.text.edits.TextEdit in project eclipse.jdt.ls by eclipse.

the class FormatterHandler method convertEdit.

private static org.eclipse.lsp4j.TextEdit convertEdit(TextEdit edit, IDocument document) {
    org.eclipse.lsp4j.TextEdit textEdit = new org.eclipse.lsp4j.TextEdit();
    if (edit instanceof ReplaceEdit) {
        ReplaceEdit replaceEdit = (ReplaceEdit) edit;
        textEdit.setNewText(replaceEdit.getText());
        int offset = edit.getOffset();
        textEdit.setRange(new Range(createPosition(document, offset), createPosition(document, offset + edit.getLength())));
    }
    return textEdit;
}
Also used : MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit) Range(org.eclipse.lsp4j.Range)

Example 79 with TextEdit

use of org.eclipse.text.edits.TextEdit in project eclipse.jdt.ls by eclipse.

the class FormatterHandler method format.

private List<org.eclipse.lsp4j.TextEdit> format(String uri, FormattingOptions options, Range range, IProgressMonitor monitor) {
    if (!preferenceManager.getPreferences().isJavaFormatEnabled()) {
        return Collections.emptyList();
    }
    ICompilationUnit cu = JDTUtils.resolveCompilationUnit(uri);
    if (cu == null) {
        return Collections.emptyList();
    }
    CodeFormatter formatter = ToolFactory.createCodeFormatter(getOptions(options, cu));
    try {
        IDocument document = JsonRpcHelpers.toDocument(cu.getBuffer());
        String lineDelimiter = TextUtilities.getDefaultLineDelimiter(document);
        IRegion region = (range == null ? new Region(0, document.getLength()) : getRegion(range, document));
        // could not calculate region abort.
        if (region == null || monitor.isCanceled()) {
            return Collections.<org.eclipse.lsp4j.TextEdit>emptyList();
        }
        String sourceToFormat = document.get();
        TextEdit format = formatter.format(CodeFormatter.K_COMPILATION_UNIT, sourceToFormat, region.getOffset(), region.getLength(), 0, lineDelimiter);
        if (format == null || format.getChildren().length == 0 || monitor.isCanceled()) {
            // nothing to return
            return Collections.<org.eclipse.lsp4j.TextEdit>emptyList();
        }
        MultiTextEdit flatEdit = TextEditUtil.flatten(format);
        return convertEdits(flatEdit.getChildren(), document);
    } catch (JavaModelException e) {
        JavaLanguageServerPlugin.logException(e.getMessage(), e);
        return Collections.emptyList();
    }
}
Also used : CodeFormatter(org.eclipse.jdt.core.formatter.CodeFormatter) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) JavaModelException(org.eclipse.jdt.core.JavaModelException) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) Region(org.eclipse.jface.text.Region) IRegion(org.eclipse.jface.text.IRegion) IDocument(org.eclipse.jface.text.IDocument) IRegion(org.eclipse.jface.text.IRegion) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit)

Example 80 with TextEdit

use of org.eclipse.text.edits.TextEdit in project eclipse.jdt.ls by eclipse.

the class ExtractMethodRefactoring method createChange.

@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.ls.core.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.ls.core.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.ls.core.internal.corext.fix.LinkedProposalPositionGroup) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) CompilationUnitChange(org.eclipse.jdt.core.refactoring.CompilationUnitChange)

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