Search in sources :

Example 21 with ITextFileBufferManager

use of org.eclipse.core.filebuffers.ITextFileBufferManager in project eclipse.platform.text by eclipse.

the class TextSearchVisitor method getOpenDocument.

private IDocument getOpenDocument(IFile file, Map<IFile, IDocument> documentsInEditors) {
    IDocument document = documentsInEditors.get(file);
    if (document == null) {
        ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
        ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(file.getFullPath(), LocationKind.IFILE);
        if (textFileBuffer != null) {
            document = textFileBuffer.getDocument();
        }
    }
    return document;
}
Also used : ITextFileBufferManager(org.eclipse.core.filebuffers.ITextFileBufferManager) ITextFileBuffer(org.eclipse.core.filebuffers.ITextFileBuffer) IDocument(org.eclipse.jface.text.IDocument)

Example 22 with ITextFileBufferManager

use of org.eclipse.core.filebuffers.ITextFileBufferManager in project eclipse.platform.text by eclipse.

the class ReplaceRefactoring method createFileChange.

private TextChange createFileChange(IFile file, Pattern pattern, Set<FileMatch> matches, RefactoringStatus resultingStatus, Collection<MatchGroup> matchGroups) throws PatternSyntaxException, CoreException {
    PositionTracker tracker = InternalSearchUI.getInstance().getPositionTracker();
    TextFileChange change = new TextFileChange(Messages.format(SearchMessages.ReplaceRefactoring_group_label_change_for_file, file.getName()), file);
    change.setEdit(new MultiTextEdit());
    ITextFileBufferManager manager = FileBuffers.getTextFileBufferManager();
    manager.connect(file.getFullPath(), LocationKind.IFILE, null);
    try {
        ITextFileBuffer textFileBuffer = manager.getTextFileBuffer(file.getFullPath(), LocationKind.IFILE);
        if (textFileBuffer == null) {
            resultingStatus.addError(Messages.format(SearchMessages.ReplaceRefactoring_error_accessing_file_buffer, file.getName()));
            return null;
        }
        IDocument document = textFileBuffer.getDocument();
        String lineDelimiter = TextUtilities.getDefaultLineDelimiter(document);
        for (FileMatch match : matches) {
            int offset = match.getOffset();
            int length = match.getLength();
            Position currentPosition = tracker.getCurrentPosition(match);
            if (currentPosition != null) {
                offset = currentPosition.offset;
                if (length != currentPosition.length) {
                    resultingStatus.addError(Messages.format(SearchMessages.ReplaceRefactoring_error_match_content_changed, file.getName()));
                    continue;
                }
            }
            String originalText = getOriginalText(document, offset, length);
            if (originalText == null) {
                resultingStatus.addError(Messages.format(SearchMessages.ReplaceRefactoring_error_match_content_changed, file.getName()));
                continue;
            }
            String replacementString = PatternConstructor.interpretReplaceEscapes(fReplaceString, originalText, lineDelimiter);
            replacementString = computeReplacementString(pattern, document, offset, replacementString);
            if (replacementString == null) {
                resultingStatus.addError(Messages.format(SearchMessages.ReplaceRefactoring_error_match_content_changed, file.getName()));
                continue;
            }
            ReplaceEdit replaceEdit = new ReplaceEdit(offset, length, replacementString);
            change.addEdit(replaceEdit);
            TextEditChangeGroup textEditChangeGroup = new TextEditChangeGroup(change, new TextEditGroup(SearchMessages.ReplaceRefactoring_group_label_match_replace, replaceEdit));
            change.addTextEditChangeGroup(textEditChangeGroup);
            matchGroups.add(new MatchGroup(textEditChangeGroup, match));
        }
    } finally {
        manager.disconnect(file.getFullPath(), LocationKind.IFILE, null);
    }
    return change;
}
Also used : ITextFileBufferManager(org.eclipse.core.filebuffers.ITextFileBufferManager) Position(org.eclipse.jface.text.Position) TextFileChange(org.eclipse.ltk.core.refactoring.TextFileChange) TextEditChangeGroup(org.eclipse.ltk.core.refactoring.TextEditChangeGroup) PositionTracker(org.eclipse.search2.internal.ui.text.PositionTracker) ITextFileBuffer(org.eclipse.core.filebuffers.ITextFileBuffer) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit) TextEditGroup(org.eclipse.text.edits.TextEditGroup) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) IDocument(org.eclipse.jface.text.IDocument)

Example 23 with ITextFileBufferManager

use of org.eclipse.core.filebuffers.ITextFileBufferManager in project eclipse.platform.text by eclipse.

the class GenericFileBufferOperationRunner method executeInContext.

private void executeInContext(Runnable runnable) {
    ITextFileBufferManager fileBufferManager = FileBuffers.getTextFileBufferManager();
    fileBufferManager.execute(runnable);
}
Also used : ITextFileBufferManager(org.eclipse.core.filebuffers.ITextFileBufferManager)

Example 24 with ITextFileBufferManager

use of org.eclipse.core.filebuffers.ITextFileBufferManager in project linuxtools by eclipse.

the class GNUHyperlinkDetector method detectHyperlinks.

/**
 * Detector using RuleBasedScanner.
 */
@Override
public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) {
    if (documentLocation == null) {
        ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
        ITextFileBuffer buffer = bufferManager.getTextFileBuffer(textViewer.getDocument());
        if (buffer == null) {
            return null;
        }
        documentLocation = buffer.getLocation().removeLastSegments(1);
    }
    IDocument thisDoc = textViewer.getDocument();
    GNUHyperlinkScanner scanner = new GNUHyperlinkScanner();
    ITypedRegion partitionInfo = null;
    try {
        partitionInfo = thisDoc.getPartition(region.getOffset());
    } catch (org.eclipse.jface.text.BadLocationException e1) {
        e1.printStackTrace();
        return null;
    }
    scanner.setRange(thisDoc, partitionInfo.getOffset(), partitionInfo.getLength());
    Token tmpToken = (Token) scanner.nextToken();
    String tokenStr = (String) tmpToken.getData();
    if (tokenStr == null) {
        return null;
    }
    // null.
    while (region.getOffset() < scanner.getTokenOffset() || region.getOffset() > scanner.getOffset() || tokenStr.equals("_other")) {
        tmpToken = (Token) scanner.nextToken();
        tokenStr = (String) tmpToken.getData();
        if (tokenStr == null)
            return null;
    }
    Region tokenRegion = new Region(scanner.getTokenOffset(), scanner.getTokenLength());
    String line = "";
    try {
        line = thisDoc.get(tokenRegion.getOffset(), tokenRegion.getLength());
    } catch (org.eclipse.jface.text.BadLocationException e1) {
        e1.printStackTrace();
        return null;
    }
    // process file link
    if (tokenStr.equals(GNUHyperlinkScanner.FILE_NAME)) {
        Region pathRegion = null;
        int lineOffset = 0;
        // cut "* " if necessary
        if (line.startsWith("* ")) {
            lineOffset = 2;
            line = line.substring(2);
        }
        pathRegion = new Region(tokenRegion.getOffset() + lineOffset, line.length());
        if (documentLocation == null)
            return null;
        // Replace any escape characters added to name
        line = line.replaceAll("\\\\(.)", "$1");
        IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
        IFile fileLoc = (IFile) root.findMember(documentLocation.append(line));
        if (fileLoc != null && fileLoc.exists()) {
            return new IHyperlink[] { new FileHyperlink(pathRegion, fileLoc) };
        }
    }
    return null;
}
Also used : IFile(org.eclipse.core.resources.IFile) ITextFileBufferManager(org.eclipse.core.filebuffers.ITextFileBufferManager) Token(org.eclipse.jface.text.rules.Token) IWorkspaceRoot(org.eclipse.core.resources.IWorkspaceRoot) IHyperlink(org.eclipse.jface.text.hyperlink.IHyperlink) ITextFileBuffer(org.eclipse.core.filebuffers.ITextFileBuffer) ITypedRegion(org.eclipse.jface.text.ITypedRegion) Region(org.eclipse.jface.text.Region) ITypedRegion(org.eclipse.jface.text.ITypedRegion) IRegion(org.eclipse.jface.text.IRegion) IDocument(org.eclipse.jface.text.IDocument)

Example 25 with ITextFileBufferManager

use of org.eclipse.core.filebuffers.ITextFileBufferManager 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)

Aggregations

ITextFileBufferManager (org.eclipse.core.filebuffers.ITextFileBufferManager)86 ITextFileBuffer (org.eclipse.core.filebuffers.ITextFileBuffer)65 IDocument (org.eclipse.jface.text.IDocument)53 IPath (org.eclipse.core.runtime.IPath)51 CoreException (org.eclipse.core.runtime.CoreException)36 BadLocationException (org.eclipse.jface.text.BadLocationException)26 IFile (org.eclipse.core.resources.IFile)22 Test (org.junit.Test)17 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)11 IOException (java.io.IOException)10 MalformedTreeException (org.eclipse.text.edits.MalformedTreeException)10 IResource (org.eclipse.core.resources.IResource)8 Path (org.eclipse.core.runtime.Path)8 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)7 SubProgressMonitor (org.eclipse.core.runtime.SubProgressMonitor)6 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)6 TextEdit (org.eclipse.text.edits.TextEdit)6 UndoEdit (org.eclipse.text.edits.UndoEdit)6 FileNotFoundException (java.io.FileNotFoundException)5 MalformedURLException (java.net.MalformedURLException)5