Search in sources :

Example 26 with MalformedTreeException

use of org.eclipse.text.edits.MalformedTreeException in project AutoRefactor by JnRouvignac.

the class TestHelper method normalizeJavaSourceCode.

public static String normalizeJavaSourceCode(String source) {
    final CodeFormatter codeFormatter = createCodeFormatter(getJava7Options());
    final TextEdit edit = // source to format
    codeFormatter.format(// source to format
    K_COMPILATION_UNIT, // source to format
    source, // source to format
    0, // source to format
    source.length(), // initial indentation and line separator //$NON-NLS-1$
    0, // initial indentation and line separator //$NON-NLS-1$
    System.getProperty("line.separator"));
    try {
        final IDocument document = new Document(source);
        edit.apply(document);
        return document.get();
    } catch (MalformedTreeException | BadLocationException e) {
        throw new RuntimeException(e);
    }
}
Also used : ToolFactory.createCodeFormatter(org.eclipse.jdt.core.ToolFactory.createCodeFormatter) CodeFormatter(org.eclipse.jdt.core.formatter.CodeFormatter) TextEdit(org.eclipse.text.edits.TextEdit) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 27 with MalformedTreeException

use of org.eclipse.text.edits.MalformedTreeException in project eclipse-pmd by acanda.

the class JavaQuickFix method fixMarkersInFile.

/**
 * Fixes all provided markers in a file.
 *
 * @param markers The markers to fix. There is at least one marker in this collection and all markers can be fixed
 *            by this quick fix.
 */
protected void fixMarkersInFile(final IFile file, final List<IMarker> markers, final IProgressMonitor monitor) {
    monitor.subTask(file.getFullPath().toOSString());
    final Optional<ICompilationUnit> optionalCompilationUnit = getCompilationUnit(file);
    if (!optionalCompilationUnit.isPresent()) {
        return;
    }
    final ICompilationUnit compilationUnit = optionalCompilationUnit.get();
    ITextFileBufferManager bufferManager = null;
    final IPath path = compilationUnit.getPath();
    try {
        bufferManager = FileBuffers.getTextFileBufferManager();
        bufferManager.connect(path, LocationKind.IFILE, null);
        final ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path, LocationKind.IFILE);
        final IDocument document = textFileBuffer.getDocument();
        final IAnnotationModel annotationModel = textFileBuffer.getAnnotationModel();
        final ASTParser astParser = ASTParser.newParser(AST.JLS4);
        astParser.setKind(ASTParser.K_COMPILATION_UNIT);
        astParser.setResolveBindings(needsTypeResolution());
        astParser.setSource(compilationUnit);
        final SubProgressMonitor parserMonitor = new SubProgressMonitor(monitor, 100);
        final CompilationUnit ast = (CompilationUnit) astParser.createAST(parserMonitor);
        parserMonitor.done();
        startFixingMarkers(ast);
        final Map<?, ?> options = compilationUnit.getJavaProject().getOptions(true);
        for (final IMarker marker : markers) {
            try {
                final MarkerAnnotation annotation = getMarkerAnnotation(annotationModel, marker);
                // if the annotation is null it means that is was deleted by a previous quick fix
                if (annotation != null) {
                    final Optional<T> node = getNodeFinder(annotationModel.getPosition(annotation)).findNode(ast);
                    if (node.isPresent()) {
                        final boolean isSuccessful = fixMarker(node.get(), document, options);
                        if (isSuccessful) {
                            marker.delete();
                        }
                    }
                }
            } finally {
                monitor.worked(100);
            }
        }
        finishFixingMarkers(ast, document, options);
        // commit changes to underlying file if it is not opened in an editor
        if (!isEditorOpen(file)) {
            final SubProgressMonitor commitMonitor = new SubProgressMonitor(monitor, 100);
            textFileBuffer.commit(commitMonitor, false);
            commitMonitor.done();
        } else {
            monitor.worked(100);
        }
    } catch (CoreException | MalformedTreeException | BadLocationException e) {
    // TODO: log error
    // PMDPlugin.getDefault().error("Error processing quickfix", e);
    } finally {
        if (bufferManager != null) {
            try {
                bufferManager.disconnect(path, LocationKind.IFILE, null);
            } catch (final CoreException e) {
            // TODO: log error
            // PMDPlugin.getDefault().error("Error processing quickfix", e);
            }
        }
    }
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IPath(org.eclipse.core.runtime.IPath) ITextFileBufferManager(org.eclipse.core.filebuffers.ITextFileBufferManager) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) IAnnotationModel(org.eclipse.jface.text.source.IAnnotationModel) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) MarkerAnnotation(org.eclipse.ui.texteditor.MarkerAnnotation) AST(org.eclipse.jdt.core.dom.AST) CoreException(org.eclipse.core.runtime.CoreException) ITextFileBuffer(org.eclipse.core.filebuffers.ITextFileBuffer) IMarker(org.eclipse.core.resources.IMarker) ASTParser(org.eclipse.jdt.core.dom.ASTParser) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 28 with MalformedTreeException

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

the class SmartSemicolonAutoEditStrategy method customizeDocumentCommand.

/*
	 * @see org.eclipse.jface.text.IAutoEditStrategy#customizeDocumentCommand(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.DocumentCommand)
	 */
public void customizeDocumentCommand(IDocument document, DocumentCommand command) {
    if (command.text == null)
        return;
    if (command.text.equals(SEMICOLON))
        fCharacter = SEMICHAR;
    else if (command.text.equals(BRACE))
        fCharacter = BRACECHAR;
    else
        return;
    //		IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
    //		if (fCharacter == SEMICHAR && !store.getBoolean(PreferenceConstants.EDITOR_SMART_SEMICOLON))
    //			return;
    //		if (fCharacter == BRACECHAR && !store.getBoolean(PreferenceConstants.EDITOR_SMART_OPENING_BRACE))
    //			return;
    //
    //		IWorkbenchPage page= JavaPlugin.getActivePage();
    //		if (page == null)
    //			return;
    //		IEditorPart part= page.getActiveEditor();
    //		if (!(part instanceof CompilationUnitEditor))
    //			return;
    //		CompilationUnitEditor editor= (CompilationUnitEditor)part;
    //		if (editor.getInsertMode() != ITextEditorExtension3.SMART_INSERT || !editor.isEditable())
    //			return;
    //		ITextEditorExtension2 extension= (ITextEditorExtension2)editor.getAdapter(ITextEditorExtension2.class);
    //		if (extension != null && !extension.validateEditorInputState())
    //			return;
    //		if (isMultilineSelection(document, command))
    //			return;
    // 1: find concerned line / position in java code, location in statement
    int pos = command.offset;
    ITextSelection line;
    try {
        IRegion l = document.getLineInformationOfOffset(pos);
        line = new TextSelection(document, l.getOffset(), l.getLength());
    } catch (BadLocationException e) {
        return;
    }
    // 2: choose action based on findings (is for-Statement?)
    // for now: compute the best position to insert the new character
    int positionInLine = computeCharacterPosition(document, line, pos - line.getOffset(), fCharacter, fPartitioning);
    int position = positionInLine + line.getOffset();
    // never position before the current position!
    if (position < pos)
        return;
    // never double already existing content
    if (alreadyPresent(document, fCharacter, position))
        return;
    // don't do special processing if what we do is actually the normal behaviour
    String insertion = adjustSpacing(document, position, fCharacter);
    if (command.offset == position && insertion.equals(command.text))
        return;
    try {
        //			final SmartBackspaceManager manager= (SmartBackspaceManager) editor.getAdapter(SmartBackspaceManager.class);
        //			if (manager != null && JavaPlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_BACKSPACE)) {
        //				TextEdit e1= new ReplaceEdit(command.offset, command.text.length(), document.get(command.offset, command.length));
        //				UndoSpec s1= new UndoSpec(command.offset + command.text.length(),
        //						new Region(command.offset, 0),
        //						new TextEdit[] {e1},
        //						0,
        //						null);
        //
        //				DeleteEdit smart= new DeleteEdit(position, insertion.length());
        //				ReplaceEdit raw= new ReplaceEdit(command.offset, command.length, command.text);
        //				UndoSpec s2= new UndoSpec(position + insertion.length(),
        //						new Region(command.offset + command.text.length(), 0),
        //						new TextEdit[] {smart, raw},
        //						2,
        //						s1);
        //				manager.register(s2);
        //			}
        // 3: modify command
        command.offset = position;
        command.length = 0;
        command.caretOffset = position;
        command.text = insertion;
        command.doit = true;
        command.owner = null;
    } catch (MalformedTreeException e) {
        JavaPlugin.log(e);
    }
}
Also used : ITextSelection(org.eclipse.che.jface.text.ITextSelection) TextSelection(org.eclipse.che.jface.text.TextSelection) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) ITextSelection(org.eclipse.che.jface.text.ITextSelection) IRegion(org.eclipse.jface.text.IRegion) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 29 with MalformedTreeException

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

the class InlineTempRefactoring method createParameterizedInvocation.

private String createParameterizedInvocation(Expression invocation, ITypeBinding[] typeArguments, CompilationUnitRewrite cuRewrite) throws JavaModelException {
    ASTRewrite rewrite = ASTRewrite.create(invocation.getAST());
    ListRewrite typeArgsRewrite = Invocations.getInferredTypeArgumentsRewrite(rewrite, invocation);
    for (int i = 0; i < typeArguments.length; i++) {
        Type typeArgumentNode = cuRewrite.getImportRewrite().addImport(typeArguments[i], cuRewrite.getAST());
        typeArgsRewrite.insertLast(typeArgumentNode, null);
    }
    if (invocation instanceof MethodInvocation) {
        MethodInvocation methodInvocation = (MethodInvocation) invocation;
        Expression expression = methodInvocation.getExpression();
        if (expression == null) {
            IMethodBinding methodBinding = methodInvocation.resolveMethodBinding();
            if (methodBinding != null && Modifier.isStatic(methodBinding.getModifiers())) {
                expression = cuRewrite.getAST().newName(cuRewrite.getImportRewrite().addImport(methodBinding.getDeclaringClass().getTypeDeclaration()));
            } else {
                expression = invocation.getAST().newThisExpression();
            }
            rewrite.set(invocation, MethodInvocation.EXPRESSION_PROPERTY, expression, null);
        }
    }
    IDocument document = new Document(fCu.getBuffer().getContents());
    final RangeMarker marker = new RangeMarker(invocation.getStartPosition(), invocation.getLength());
    IJavaProject project = fCu.getJavaProject();
    TextEdit[] rewriteEdits = rewrite.rewriteAST(document, project.getOptions(true)).removeChildren();
    marker.addChildren(rewriteEdits);
    try {
        marker.apply(document, TextEdit.UPDATE_REGIONS);
        String rewrittenInitializer = document.get(marker.getOffset(), marker.getLength());
        IRegion region = document.getLineInformation(document.getLineOfOffset(marker.getOffset()));
        int oldIndent = Strings.computeIndentUnits(document.get(region.getOffset(), region.getLength()), project);
        //$NON-NLS-1$
        return Strings.changeIndent(rewrittenInitializer, oldIndent, project, "", TextUtilities.getDefaultLineDelimiter(document));
    } catch (MalformedTreeException e) {
        JavaPlugin.log(e);
    } catch (BadLocationException e) {
        JavaPlugin.log(e);
    }
    //fallback:
    return fCu.getBuffer().getText(invocation.getStartPosition(), invocation.getLength());
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) RangeMarker(org.eclipse.text.edits.RangeMarker) Document(org.eclipse.jface.text.Document) IDocument(org.eclipse.jface.text.IDocument) IRegion(org.eclipse.jface.text.IRegion) ArrayType(org.eclipse.jdt.core.dom.ArrayType) Type(org.eclipse.jdt.core.dom.Type) IJavaProject(org.eclipse.jdt.core.IJavaProject) Expression(org.eclipse.jdt.core.dom.Expression) CastExpression(org.eclipse.jdt.core.dom.CastExpression) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) TextEdit(org.eclipse.text.edits.TextEdit) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 30 with MalformedTreeException

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

the class TextChange method perform.

/**
	 * {@inheritDoc}
	 */
public Change perform(IProgressMonitor pm) throws CoreException {
    //$NON-NLS-1$
    pm.beginTask("", 3);
    IDocument document = null;
    try {
        document = acquireDocument(new SubProgressMonitor(pm, 1));
        UndoEdit undo = performEdits(document);
        commit(document, new SubProgressMonitor(pm, 1));
        return createUndoChange(undo);
    } catch (BadLocationException e) {
        throw Changes.asCoreException(e);
    } catch (MalformedTreeException e) {
        throw Changes.asCoreException(e);
    } finally {
        releaseDocument(document, new SubProgressMonitor(pm, 1));
        pm.done();
    }
}
Also used : MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) UndoEdit(org.eclipse.text.edits.UndoEdit) IDocument(org.eclipse.jface.text.IDocument) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) BadLocationException(org.eclipse.jface.text.BadLocationException)

Aggregations

MalformedTreeException (org.eclipse.text.edits.MalformedTreeException)52 BadLocationException (org.eclipse.jface.text.BadLocationException)38 IDocument (org.eclipse.jface.text.IDocument)25 TextEdit (org.eclipse.text.edits.TextEdit)19 CoreException (org.eclipse.core.runtime.CoreException)12 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)12 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)11 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)11 Document (org.eclipse.jface.text.Document)11 ReplaceEdit (org.eclipse.text.edits.ReplaceEdit)11 Test (org.junit.Test)11 ITextFileBufferManager (org.eclipse.core.filebuffers.ITextFileBufferManager)10 MultiTextEdit (org.eclipse.text.edits.MultiTextEdit)10 ITextFileBuffer (org.eclipse.core.filebuffers.ITextFileBuffer)9 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)9 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)8 InsertEdit (org.eclipse.text.edits.InsertEdit)8 IPath (org.eclipse.core.runtime.IPath)7 ASTNode (org.eclipse.jdt.core.dom.ASTNode)7 ArrayList (java.util.ArrayList)6