Search in sources :

Example 86 with TextEdit

use of org.eclipse.text.edits.TextEdit in project jbosstools-hibernate by jbosstools.

the class SaveQueryEditorListener method propertyChanged.

/* (non-Javadoc)
	 * @see org.eclipse.ui.IPropertyListener#propertyChanged(java.lang.Object, int)
	 */
public void propertyChanged(Object source, int propId) {
    if (IEditorPart.PROP_DIRTY == propId && !editor.isDirty()) {
        IDocumentProvider docProvider = fromEditorPart.getDocumentProvider();
        final IFile file = ((IFileEditorInput) fromEditorPart.getEditorInput()).getFile();
        final IDocument doc = docProvider.getDocument(fromEditorPart.getEditorInput());
        boolean isDocChanged = true;
        try {
            if (query.equals(doc.get(position.x, position.y))) {
                isDocChanged = false;
            }
        } catch (BadLocationException e1) {
        // document changed and we can get the exception
        }
        final String editorTitle = fromEditorPart.getTitle();
        final String editor_name = editor instanceof HQLEditor ? JdtUiMessages.SaveQueryEditorListener_hql_editor : JdtUiMessages.SaveQueryEditorListener_cri_editor;
        if (isDocChanged) {
            String information_message = NLS.bind(JdtUiMessages.SaveQueryEditorListener_replacequestion_confirm, editorTitle);
            MessageDialog.openInformation(null, JdtUiMessages.SaveQueryEditorListener_replacetitle_info, information_message);
            return;
        }
        final String newQuery = editor.getEditorText();
        final String wizard_title = NLS.bind(JdtUiMessages.SaveQueryEditorListener_refactoringtitle, editor_name);
        Refactoring ref = new Refactoring() {

            @Override
            public RefactoringStatus checkFinalConditions(IProgressMonitor pm) {
                return RefactoringStatus.create(Status.OK_STATUS);
            }

            @Override
            public RefactoringStatus checkInitialConditions(IProgressMonitor pm) {
                return RefactoringStatus.create(Status.OK_STATUS);
            }

            @Override
            public Change createChange(IProgressMonitor pm) {
                String change_name = NLS.bind(JdtUiMessages.SaveQueryEditorListener_change_name, editor_name, editorTitle);
                DocumentChange change = new DocumentChange(change_name, doc);
                TextEdit replaceEdit = new ReplaceEdit(position.x, position.y, newQuery);
                change.setEdit(replaceEdit);
                String cc_name = NLS.bind(JdtUiMessages.SaveQueryEditorListener_composite_change_name, editor_name);
                MultiStateTextFileChange mChange = new MultiStateTextFileChange(cc_name, file);
                mChange.addChange(change);
                return mChange;
            }

            @Override
            public String getName() {
                return JdtUiMessages.SaveQueryEditorListener_composite_change_name;
            }
        };
        RefactoringWizard wizard = new RefactoringWizard(ref, RefactoringWizard.DIALOG_BASED_USER_INTERFACE) {

            @Override
            protected void addUserInputPages() {
                UserInputWizardPage page = new UserInputWizardPage(wizard_title) {

                    public void createControl(Composite parent) {
                        Composite container = new Composite(parent, SWT.NULL);
                        GridLayout layout = new GridLayout();
                        container.setLayout(layout);
                        layout.numColumns = 1;
                        layout.verticalSpacing = 9;
                        Label label = new Label(container, SWT.NULL);
                        label.setText(NLS.bind(JdtUiMessages.SaveQueryEditorListener_replacequestion, editor_name, editorTitle));
                        setControl(container);
                    }
                };
                addPage(page);
            }
        };
        wizard.setWindowTitle(wizard_title);
        wizard.setDefaultPageTitle(wizard_title);
        IWorkbenchWindow win = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
        if (new RefactoringStarter().activate(wizard, win.getShell(), wizard_title, RefactoringSaveHelper.SAVE_ALL)) {
            query = newQuery;
            position.y = query.length();
            fromEditorPart.doSave(null);
        } else {
            if (editor.getDocumentProvider() instanceof TextFileDocumentProvider) {
                ((TextFileDocumentProvider) editor.getDocumentProvider()).setCanSaveDocument(editor.getEditorInput());
            }
        }
    }
}
Also used : MultiStateTextFileChange(org.eclipse.ltk.core.refactoring.MultiStateTextFileChange) UserInputWizardPage(org.eclipse.ltk.ui.refactoring.UserInputWizardPage) IWorkbenchWindow(org.eclipse.ui.IWorkbenchWindow) IFile(org.eclipse.core.resources.IFile) Composite(org.eclipse.swt.widgets.Composite) Label(org.eclipse.swt.widgets.Label) RefactoringStarter(org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter) DocumentChange(org.eclipse.ltk.core.refactoring.DocumentChange) TextFileDocumentProvider(org.eclipse.ui.editors.text.TextFileDocumentProvider) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) GridLayout(org.eclipse.swt.layout.GridLayout) IDocumentProvider(org.eclipse.ui.texteditor.IDocumentProvider) RefactoringWizard(org.eclipse.ltk.ui.refactoring.RefactoringWizard) IFileEditorInput(org.eclipse.ui.IFileEditorInput) TextEdit(org.eclipse.text.edits.TextEdit) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit) HQLEditor(org.hibernate.eclipse.hqleditor.HQLEditor) Refactoring(org.eclipse.ltk.core.refactoring.Refactoring) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 87 with TextEdit

use of org.eclipse.text.edits.TextEdit in project eclipse-cs by checkstyle.

the class AbstractQuickfixTestCase method testQuickfix.

protected void testQuickfix(InputStream testdataStream, AbstractASTResolution quickfix) throws Exception {
    QuickfixTestData[] testdata = getTestData(testdataStream);
    for (int i = 0; i < testdata.length; i++) {
        org.eclipse.jface.text.Document doc = new org.eclipse.jface.text.Document(testdata[i].input);
        ASTParser parser = ASTParser.newParser(AST.JLS3);
        parser.setSource(doc.get().toCharArray());
        CompilationUnit compUnit = (CompilationUnit) parser.createAST(new NullProgressMonitor());
        compUnit.recordModifications();
        IRegion region = doc.getLineInformation(testdata[i].line);
        int markerStartOffset = region.getOffset() + testdata[i].position;
        compUnit.accept(quickfix.handleGetCorrectingASTVisitor(region, markerStartOffset));
        Map<String, String> options = new HashMap<String, String>();
        options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.SPACE);
        options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, "4");
        options.put(DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_CASES, "true");
        options.put(DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_SWITCH, "true");
        TextEdit edit = compUnit.rewrite(doc, options);
        edit.apply(doc);
        Assert.assertEquals(testdata[i].result, doc.get());
    }
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) HashMap(java.util.HashMap) Document(org.w3c.dom.Document) IRegion(org.eclipse.jface.text.IRegion) TextEdit(org.eclipse.text.edits.TextEdit) ASTParser(org.eclipse.jdt.core.dom.ASTParser)

Example 88 with TextEdit

use of org.eclipse.text.edits.TextEdit in project eclipse-cs by checkstyle.

the class AbstractASTResolution method run.

/**
 * {@inheritDoc}
 */
@Override
public void run(IMarker marker) {
    IResource resource = marker.getResource();
    if (!(resource instanceof IFile)) {
        return;
    }
    ICompilationUnit compilationUnit = getCompilationUnit(marker);
    if (compilationUnit == null) {
        return;
    }
    ITextFileBufferManager bufferManager = null;
    IPath path = compilationUnit.getPath();
    try {
        final IProgressMonitor monitor = new NullProgressMonitor();
        // open the file the editor
        JavaUI.openInEditor(compilationUnit);
        // reimplemented according to this article
        // http://www.eclipse.org/articles/Article-JavaCodeManipulation_AST/index.html
        bufferManager = FileBuffers.getTextFileBufferManager();
        bufferManager.connect(path, null);
        ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path);
        IDocument document = textFileBuffer.getDocument();
        IAnnotationModel annotationModel = textFileBuffer.getAnnotationModel();
        MarkerAnnotation annotation = getMarkerAnnotation(annotationModel, marker);
        // by a previous quickfix
        if (annotation == null) {
            return;
        }
        Position pos = annotationModel.getPosition(annotation);
        final IRegion lineInfo = document.getLineInformationOfOffset(pos.getOffset());
        final int markerStart = pos.getOffset();
        ASTParser astParser = ASTParser.newParser(AST.JLS3);
        astParser.setKind(ASTParser.K_COMPILATION_UNIT);
        astParser.setSource(compilationUnit);
        CompilationUnit ast = (CompilationUnit) astParser.createAST(monitor);
        ast.recordModifications();
        ast.accept(handleGetCorrectingASTVisitor(lineInfo, markerStart));
        // rewrite all recorded changes to the document
        TextEdit edit = ast.rewrite(document, compilationUnit.getJavaProject().getOptions(true));
        edit.apply(document);
        // commit changes to underlying file
        if (mAutoCommit) {
            textFileBuffer.commit(monitor, false);
        }
    } catch (CoreException e) {
        CheckstyleLog.log(e, Messages.AbstractASTResolution_msgErrorQuickfix);
    } catch (MalformedTreeException e) {
        CheckstyleLog.log(e, Messages.AbstractASTResolution_msgErrorQuickfix);
    } catch (BadLocationException e) {
        CheckstyleLog.log(e, Messages.AbstractASTResolution_msgErrorQuickfix);
    } finally {
        if (bufferManager != null) {
            try {
                bufferManager.disconnect(path, null);
            } catch (CoreException e) {
                // $NON-NLS-1$
                CheckstyleLog.log(e, "Error processing quickfix");
            }
        }
    }
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) IFile(org.eclipse.core.resources.IFile) IPath(org.eclipse.core.runtime.IPath) ITextFileBufferManager(org.eclipse.core.filebuffers.ITextFileBufferManager) Position(org.eclipse.jface.text.Position) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) IAnnotationModel(org.eclipse.jface.text.source.IAnnotationModel) IRegion(org.eclipse.jface.text.IRegion) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) MarkerAnnotation(org.eclipse.ui.texteditor.MarkerAnnotation) CoreException(org.eclipse.core.runtime.CoreException) TextEdit(org.eclipse.text.edits.TextEdit) ITextFileBuffer(org.eclipse.core.filebuffers.ITextFileBuffer) ASTParser(org.eclipse.jdt.core.dom.ASTParser) IResource(org.eclipse.core.resources.IResource) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 89 with TextEdit

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

the class FixedContentFormatter method format.

/**
 * This method makes sure that no changes are applied (no dirty state), if there are no changes. This fixes bug
 * GHOLD-272
 */
@Override
public void format(IDocument document, IRegion region) {
    IXtextDocument doc = (IXtextDocument) document;
    TextEdit e = doc.priorityReadOnly(new FormattingUnitOfWork(doc, region));
    if (e == null)
        return;
    if (e instanceof ReplaceEdit) {
        ReplaceEdit r = (ReplaceEdit) e;
        if ((r.getOffset() == 0) && (r.getLength() == 0) && (r.getText().isEmpty())) {
            return;
        }
    }
    try {
        e.apply(document);
    } catch (BadLocationException ex) {
        throw new RuntimeException(ex);
    }
}
Also used : MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) TextEdit(org.eclipse.text.edits.TextEdit) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit) BadLocationException(org.eclipse.jface.text.BadLocationException) IXtextDocument(org.eclipse.xtext.ui.editor.model.IXtextDocument)

Example 90 with TextEdit

use of org.eclipse.text.edits.TextEdit in project evosuite by EvoSuite.

the class ResolutionMarkerThrowsException method run.

@Override
public void run(IMarker marker) {
    // TODO Auto-generated method stub
    IResource res = marker.getResource();
    try {
        String markerMessage = (String) marker.getAttribute(IMarker.MESSAGE);
        String exception = markerMessage.split(" ")[0];
        String[] exceptionPackageArray = exception.split("\\.");
        String exceptionPackage = "";
        for (int i = 0; i < exceptionPackageArray.length - 1; i++) {
            exceptionPackage += exceptionPackageArray[i] + ".";
        }
        exception = exception.substring(exceptionPackage.length());
        System.out.println("Package: " + exceptionPackage + ", Exception: " + exception);
        ICompilationUnit icomp = CompilationUnitManager.getICompilationUnit(res);
        CompilationUnit compunit = CompilationUnitManager.getCompilationUnit(res);
        int position = marker.getAttribute(IMarker.CHAR_START, 0) + 1;
        if (position == 1) {
            int line = marker.getAttribute(IMarker.LINE_NUMBER, 0);
            position = compunit.getPosition(line, 0);
        }
        AST ast = compunit.getAST();
        ASTRewrite rewriter = ASTRewrite.create(ast);
        IJavaElement element = icomp.getElementAt(position);
        IJavaElement method = getMethod(element);
        // TypeDeclaration td = (TypeDeclaration) compunit.types().get(0);
        TypeDeclaration td = (TypeDeclaration) compunit.types().get(0);
        MethodDeclaration md = td.getMethods()[0];
        int counter = 1;
        while (!md.getName().getFullyQualifiedName().equals(method.getElementName()) && counter < td.getMethods().length) {
            md = td.getMethods()[counter];
            System.out.println(md.getName().getFullyQualifiedName() + " " + method.getElementName());
            counter++;
        }
        ListRewrite lr = rewriter.getListRewrite(md, MethodDeclaration.THROWN_EXCEPTIONS_PROPERTY);
        ImportDeclaration id = ast.newImportDeclaration();
        id.setName(ast.newName(exceptionPackage + exception));
        ListRewrite lrClass = rewriter.getListRewrite(compunit, CompilationUnit.TYPES_PROPERTY);
        lrClass.insertAt(id, 0, null);
        Statement s = (Statement) rewriter.createStringPlaceholder(exception, ASTNode.EMPTY_STATEMENT);
        lr.insertAt(s, 0, null);
        System.out.println("MD: " + md.getName() + "\nList: " + lr.getOriginalList());
        ITextFileBufferManager bm = FileBuffers.getTextFileBufferManager();
        IPath path = compunit.getJavaElement().getPath();
        try {
            bm.connect(path, null, null);
            ITextFileBuffer textFileBuffer = bm.getTextFileBuffer(path, null);
            IDocument document = textFileBuffer.getDocument();
            TextEdit edits = rewriter.rewriteAST(document, null);
            edits.apply(document);
            textFileBuffer.commit(null, false);
        } catch (CoreException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MalformedTreeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadLocationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                bm.disconnect(path, null, null);
            } catch (CoreException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        // (4)
        }
        System.out.println(lr.getRewrittenList() + "\nPosition: " + position + "\nEdits: " + rewriter.toString());
    } catch (JavaModelException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (CoreException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IJavaElement(org.eclipse.jdt.core.IJavaElement) AST(org.eclipse.jdt.core.dom.AST) JavaModelException(org.eclipse.jdt.core.JavaModelException) IPath(org.eclipse.core.runtime.IPath) ITextFileBufferManager(org.eclipse.core.filebuffers.ITextFileBufferManager) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) Statement(org.eclipse.jdt.core.dom.Statement) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) IOException(java.io.IOException) CoreException(org.eclipse.core.runtime.CoreException) TextEdit(org.eclipse.text.edits.TextEdit) ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration) ITextFileBuffer(org.eclipse.core.filebuffers.ITextFileBuffer) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) TypeDeclaration(org.eclipse.jdt.core.dom.TypeDeclaration) IResource(org.eclipse.core.resources.IResource) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException)

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