/** * Applies all given changes to the given document. This method assumes that 'changes' contains only changes * intended for the given document; the actual URI stored in the changes is ignored. */ public void applyAllInSameDocument(Collection<? extends IAtomicChange> changes, IDocument document) throws BadLocationException { DocumentRewriteSession rewriteSession = null; try { // prepare if (document instanceof IDocumentExtension4) { rewriteSession = ((IDocumentExtension4) document).startRewriteSession( DocumentRewriteSessionType.UNRESTRICTED); } // perform replacements for (IAtomicChange currRepl : changes) { currRepl.apply(document); } } finally { // cleanup if (rewriteSession != null) ((IDocumentExtension4) document).stopRewriteSession(rewriteSession); } }
private ImportRewriter(IDocument document, Resource resource) { if (document instanceof IDocumentExtension4) { lineDelimiter = ((IDocumentExtension4) document).getDefaultLineDelimiter(); } else { lineDelimiter = Strings.newLine(); } this.script = (Script) resource.getContents().get(0); this.existingImports = Lists.newArrayList(); for (ScriptElement element : script.getScriptElements()) { if (element instanceof ImportDeclaration) existingImports.add((ImportDeclaration) element); } this.requestedImports = Sets.newLinkedHashSet(); this.lazySpacer = new Lazy<>(() -> spacerPreference.getSpacingPreference(resource)); }
public void updateModel(String prefix, String editablePart, String suffix) { IDocument document = this.viewer.getDocument(); if (this.insertLineBreaks) { String delimiter = document.getLegalLineDelimiters()[0]; if (document instanceof IDocumentExtension4) { delimiter = ((IDocumentExtension4) document).getDefaultLineDelimiter(); } prefix = prefix + delimiter; suffix = delimiter + suffix; } String model = prefix + editablePart + suffix; this.viewer.setRedraw(false); this.viewer.getUndoManager().disconnect(); document.set(model); this.viewer.setVisibleRegion(prefix.length(), editablePart.length()); this.viewer.getUndoManager().connect(this.viewer); this.viewer.setRedraw(true); }
public void updatePrefix(String prefix) { try { IDocument document = this.viewer.getDocument(); IRegion visibleRegion = this.viewer.getVisibleRegion(); String editablePart = document.get(visibleRegion.getOffset(), visibleRegion.getLength()); int suffixOffset = visibleRegion.getOffset() + visibleRegion.getLength(); String suffix = ""; if (document.getLength() - suffixOffset > 0) { suffix = document.get(suffixOffset, document.getLength() - suffixOffset); if (this.insertLineBreaks) { String delimiter = document.getLegalLineDelimiters()[0]; if (document instanceof IDocumentExtension4) { delimiter = ((IDocumentExtension4) document).getDefaultLineDelimiter(); } suffix = suffix.substring(delimiter.length()); } } updateModel(prefix, editablePart, suffix); } catch (BadLocationException e) { throw new RuntimeException(e); } }
public static BufferValidationState create(IFile file) { ITextFileBuffer buffer = getBuffer(file); if (buffer == null) { return new ModificationStampValidationState(file); } else { IDocument document = buffer.getDocument(); if (document instanceof IDocumentExtension4) { return new ModificationStampValidationState(file); } else { if (buffer.isDirty()) { return new NoStampValidationState(file); } else { return new ModificationStampValidationState(file); } } } }
public RefactoringStatus isValid(boolean needsSaving, boolean resilientForDerived) throws CoreException { RefactoringStatus result = super.isValid(needsSaving, resilientForDerived); if (result.hasFatalError()) return result; ModificationStamp currentStamp = getModificationStamp(); // we don't need to check the kind here since the document stamp // and file stamp are in sync for documents implementing // IDocumentExtension4. If both are file stamps the file must // not be dirty if (fModificationStamp.getValue() != currentStamp.getValue() // we know here that the stamp value are equal. However, if // the stamp is a null stamp then the king must be equal as well. || (fModificationStamp.isFileStamp() && fModificationStamp.getValue() == IResource.NULL_STAMP && !currentStamp.isFileStamp()) || (fModificationStamp.isDocumentStamp() && fModificationStamp.getValue() == IDocumentExtension4.UNKNOWN_MODIFICATION_STAMP && !currentStamp.isDocumentStamp()) || (fModificationStamp.isFileStamp() && currentStamp.isFileStamp() && isDirty(fFile))) { result.addFatalError( Messages.format( RefactoringCoreMessages.TextChanges_error_content_changed, BasicElementLabels.getPathLabel(fFile.getFullPath(), false))); } return result; }
public void checkModificationStamp(RefactoringStatus status, long stampToMatch) { if (fKind == DOCUMENT) { if (stampToMatch != IDocumentExtension4.UNKNOWN_MODIFICATION_STAMP && fModificationStamp != stampToMatch) { status.addFatalError( Messages.format( RefactoringCoreMessages.ResourceChange_error_has_been_modified, BasicElementLabels.getPathLabel(fResource.getFullPath(), false))); } } else { if (stampToMatch != IResource.NULL_STAMP && fModificationStamp != stampToMatch) { status.addFatalError( Messages.format( RefactoringCoreMessages.ResourceChange_error_has_been_modified, BasicElementLabels.getPathLabel(fResource.getFullPath(), false))); } } }
private void initializeFile(IFile file) { fTextFileBuffer = getBuffer(file); if (fTextFileBuffer == null) { initializeResource(file); } else { IDocument document = fTextFileBuffer.getDocument(); fDirty = fTextFileBuffer.isDirty(); fReadOnly = Resources.isReadOnly(file); if (document instanceof IDocumentExtension4) { fKind = DOCUMENT; fModificationStamp = ((IDocumentExtension4) document).getModificationStamp(); } else { fKind = RESOURCE; fModificationStamp = file.getModificationStamp(); } } }
/** * Executes the text edits on the given document. Subclasses that override this method should call * <code>super.performEdits(document)</code>. * * @param document the document * @return an object representing the undo of the executed edits * @exception MalformedTreeException is thrown if the edit tree isn't in a valid state. This * exception is thrown before any edit is executed. So the document is still in its original * state. * @exception BadLocationException is thrown if one of the edits in the tree can't be executed. * The state of the document is undefined if this exception is thrown. * @since 3.5 */ protected UndoEdit performEdits(IDocument document) throws BadLocationException, MalformedTreeException { DocumentRewriteSession session = null; try { if (document instanceof IDocumentExtension4) { session = ((IDocumentExtension4) document) .startRewriteSession(DocumentRewriteSessionType.UNRESTRICTED); } LinkedModeModel.closeAllModels(document); TextEditProcessor processor = createTextEditProcessor(document, TextEdit.CREATE_UNDO, false); return processor.performEdits(); } finally { if (session != null) { ((IDocumentExtension4) document).stopRewriteSession(session); } } }
private void performEdit(IDocument document, long oldFileValue, LinkedList<UndoEdit> editCollector, long[] oldDocValue, boolean[] setContentStampSuccess) throws MalformedTreeException, BadLocationException, CoreException { if (document instanceof IDocumentExtension4) { oldDocValue[0]= ((IDocumentExtension4)document).getModificationStamp(); } else { oldDocValue[0]= oldFileValue; } // perform the changes for (int index= 0; index < fUndos.length; index++) { UndoEdit edit= fUndos[index]; UndoEdit redo= edit.apply(document, TextEdit.CREATE_UNDO); editCollector.addFirst(redo); } if (document instanceof IDocumentExtension4 && fDocumentStamp != IDocumentExtension4.UNKNOWN_MODIFICATION_STAMP) { try { ((IDocumentExtension4)document).replace(0, 0, "", fDocumentStamp); //$NON-NLS-1$ setContentStampSuccess[0]= true; } catch (BadLocationException e) { throw wrapBadLocationException(e); } } }
private long getDocumentStamp(IFile file, IProgressMonitor monitor) throws CoreException { final ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager(); final IPath path= file.getFullPath(); monitor.beginTask("", 2); //$NON-NLS-1$ ITextFileBuffer buffer= null; try { manager.connect(path, LocationKind.IFILE, new SubProgressMonitor(monitor, 1)); buffer= manager.getTextFileBuffer(path, LocationKind.IFILE); IDocument document= buffer.getDocument(); if (document instanceof IDocumentExtension4) { return ((IDocumentExtension4)document).getModificationStamp(); } else { return file.getModificationStamp(); } } finally { if (buffer != null) manager.disconnect(path, LocationKind.IFILE, new SubProgressMonitor(monitor, 1)); monitor.done(); } }
void removeOccurrenceAnnotations() { fMarkOccurrenceModificationStamp= IDocumentExtension4.UNKNOWN_MODIFICATION_STAMP; fMarkOccurrenceTargetRegion= null; IDocumentProvider documentProvider= getDocumentProvider(); if (documentProvider == null) return; IAnnotationModel annotationModel= documentProvider.getAnnotationModel(getEditorInput()); if (annotationModel == null || fOccurrenceAnnotations == null) return; synchronized (getLockObject(annotationModel)) { if (annotationModel instanceof IAnnotationModelExtension) { ((IAnnotationModelExtension)annotationModel).replaceAnnotations(fOccurrenceAnnotations, null); } else { for (int i= 0, length= fOccurrenceAnnotations.length; i < length; i++) annotationModel.removeAnnotation(fOccurrenceAnnotations[i]); } fOccurrenceAnnotations= null; } }
public DocCopy(IDocument document) { this.contents = document.get(); this.document = document; categoryToPos = new HashMap<>(); String[] positionCategories = document.getPositionCategories(); for (String string : positionCategories) { try { categoryToPos.put(string, document.getPositions(string)); } catch (BadPositionCategoryException e) { Log.log(e); } } IDocumentExtension4 doc4 = (IDocumentExtension4) document; modificationStamp = doc4.getModificationStamp(); }
private void initializeFile(IFile file) { fTextFileBuffer = getBuffer(file); if (fTextFileBuffer == null) { initializeResource(file); } else { IDocument document = fTextFileBuffer.getDocument(); fDirty = fTextFileBuffer.isDirty(); fReadOnly = isReadOnly(file); if (document instanceof IDocumentExtension4) { fKind = DOCUMENT; fModificationStamp = ((IDocumentExtension4) document).getModificationStamp(); } else { fKind = RESOURCE; fModificationStamp = file.getModificationStamp(); } } }
public long getModificationStamp(IResource resource) { if (!(resource instanceof IFile)) { return resource.getModificationStamp(); } IFile file = (IFile) resource; ITextFileBuffer buffer = getBuffer(file); if (buffer == null) { return file.getModificationStamp(); } else { IDocument document = buffer.getDocument(); if (document instanceof IDocumentExtension4) { return ((IDocumentExtension4) document).getModificationStamp(); } else { return file.getModificationStamp(); } } }
private void findAndDeleteUnusedImports(PySelection ps, PyEdit edit, IDocumentExtension4 doc, IFile f) throws Exception { Iterator<MarkerAnnotationAndPosition> it; if (edit != null) { it = edit.getPySourceViewer().getMarkerIterator(); } else { IMarker markers[] = f.findMarkers(IMiscConstants.PYDEV_ANALYSIS_PROBLEM_MARKER, true, IResource.DEPTH_ZERO); MarkerAnnotationAndPosition maap[] = new MarkerAnnotationAndPosition[markers.length]; int ix = 0; for (IMarker m : markers) { int start = (Integer) m.getAttribute(IMarker.CHAR_START); int end = (Integer) m.getAttribute(IMarker.CHAR_END); maap[ix++] = new MarkerAnnotationAndPosition(new MarkerAnnotation(m), new Position(start, end - start)); } it = Arrays.asList(maap).iterator(); } ArrayList<MarkerAnnotationAndPosition> unusedImportsMarkers = getUnusedImports(it); sortInReverseDocumentOrder(unusedImportsMarkers); deleteImports(doc, ps, unusedImportsMarkers); }
@Override protected boolean run(IMarker marker, AbstractTextEditor editor, IDocument doc) { String delimiter = ((IDocumentExtension4) doc).getDefaultLineDelimiter(); int offset = marker.getAttribute(IMarker.CHAR_END, -1); StyledText text = (StyledText) editor.getAdapter(Control.class); text.getDisplay().syncExec(() -> { MarkerUtils.applyEdits(doc, new ReplaceEdit(offset, 0, delimiter)); }); return true; }
public UnchangedElementListener(ElementInfo element) { this.element = element; if (element.fDocument instanceof IDocumentExtension4) { modificationStamp = ((IDocumentExtension4) element.fDocument).getModificationStamp(); } else { modificationStamp = IDocumentExtension4.UNKNOWN_MODIFICATION_STAMP; } }
public void assertModelInSyncWithDocument(IDocument document, XtextResource resource, final ReconcilerReplaceRegion region) { if (document instanceof IDocumentExtension4 && resource != null) { long beforeGet = ((IDocumentExtension4) document).getModificationStamp(); final String documentContent = document.get(); long afterGet = ((IDocumentExtension4) document).getModificationStamp(); if (beforeGet == afterGet && beforeGet == resource.getModificationStamp()) { IParseResult parseResult = resource.getParseResult(); if (parseResult != null) { ICompositeNode rootNode = parseResult.getRootNode(); final String resourceContent = rootNode.getText(); if (!resourceContent.equals(documentContent)) { new DisplayRunnable() { @Override protected void run() throws Exception { LOG.error("XtextDocument and XtextResource have run out of sync:\n" + DiffUtil.diff(documentContent, resourceContent)); LOG.error("Events: \n\t" + Joiner.on("\n\t").join(region.getDocumentEvents())); LOG.error("ReplaceRegion: \n\t'" + region + "'" ); MessageDialog.openError( Display.getCurrent().getActiveShell(), "XtextReconcilerDebugger", "XtextDocument and XtextResource have run out of sync." + "\n\nSee log for details."); } }.syncExec(); } else { System.out.println("Model and document are in sync"); } } } } }
protected UndoEdit performEdits(IDocument document) throws BadLocationException, MalformedTreeException { DocumentRewriteSession session= null; try { if (document instanceof IDocumentExtension4) { session= ((IDocumentExtension4)document).startRewriteSession( DocumentRewriteSessionType.UNRESTRICTED); } return undoEdit.apply(document); } finally { if (session != null) { ((IDocumentExtension4)document).stopRewriteSession(session); } } }
@Override public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException { pm.beginTask("", 1); RefactoringStatus refactoringStatus = new RefactoringStatus(); if(document instanceof IDocumentExtension4 && ((IDocumentExtension4) document).getModificationStamp() != modificationStamp) refactoringStatus.addFatalError("The content of the document has changed."); pm.worked(1); return refactoringStatus; }
public static boolean set(IDocument document, ContentStamp s) throws CoreException { if (!(s instanceof ContentStampImpl)) return false; ContentStampImpl stamp = (ContentStampImpl) s; if (document instanceof IDocumentExtension4 && stamp.isDocumentStamp()) { try { ((IDocumentExtension4) document).replace(0, 0, "", stamp.getValue()); // $NON-NLS-1$ return true; } catch (BadLocationException e) { throw Changes.asCoreException(e); } } return false; }
protected ModificationStamp getModificationStamp() { ITextFileBuffer buffer = getBuffer(fFile); if (buffer == null) { return ModificationStamp.createFile(fFile.getModificationStamp()); } else { IDocument document = buffer.getDocument(); if (document instanceof IDocumentExtension4) { return ModificationStamp.createDocument( ((IDocumentExtension4) document).getModificationStamp()); } else { return ModificationStamp.createFile(fFile.getModificationStamp()); } } }
private long getModificationStamp(IResource resource) { if (!(resource instanceof IFile)) return resource.getModificationStamp(); IFile file = (IFile) resource; ITextFileBuffer buffer = getBuffer(file); if (buffer == null) { return file.getModificationStamp(); } else { IDocument document = buffer.getDocument(); if (document instanceof IDocumentExtension4) { return ((IDocumentExtension4) document).getModificationStamp(); } else { return file.getModificationStamp(); } } }
private void performChangesInSynchronizationContext( final IDocument document, final LinkedList undoList, final boolean preview) throws BadLocationException { DocumentRewriteSession session = null; try { if (document instanceof IDocumentExtension4) session = ((IDocumentExtension4) document) .startRewriteSession(DocumentRewriteSessionType.UNRESTRICTED); for (final Iterator iterator = fChanges.iterator(); iterator.hasNext(); ) { final ComposableBufferChange change = (ComposableBufferChange) iterator.next(); final UndoEdit edit = createTextEditProcessor( change, document, undoList != null ? TextEdit.CREATE_UNDO : TextEdit.NONE, preview) .performEdits(); if (undoList != null) undoList.addFirst(edit); } } finally { if (session != null) ((IDocumentExtension4) document).stopRewriteSession(session); } }
@Override protected void doSetInput(IEditorInput input) throws CoreException { synchronized (modificationStampLock) { // Reset our cache when a new input is set. lastModificationStamp = IDocumentExtension4.UNKNOWN_MODIFICATION_STAMP; lastAstForModificationStamp = null; } super.doSetInput(input); }
public ParseResult getParseResult() { try { IDocument document = getDocument(); if (document == null) { return null; } long modificationStamp = IDocumentExtension4.UNKNOWN_MODIFICATION_STAMP; if (document instanceof IDocumentExtension4) { synchronized (modificationStampLock) { IDocumentExtension4 iDocumentExtension = (IDocumentExtension4) document; modificationStamp = iDocumentExtension.getModificationStamp(); if (modificationStamp != IDocumentExtension4.UNKNOWN_MODIFICATION_STAMP && modificationStamp == lastModificationStamp) { return lastAstForModificationStamp; } } } // Don't synchronize the actual parse! ParseResult ast = doGetAST(document); synchronized (modificationStampLock) { lastAstForModificationStamp = ast; lastModificationStamp = modificationStamp; return lastAstForModificationStamp; } } catch (Throwable e) { IdeLog.logTrace(CommonEditorPlugin.getDefault(), e.getMessage(), e, IDebugScopes.AST); } return null; }
public String getDefaultLineDelimiter(IDocument document) { if (document instanceof IDocumentExtension4) return ((IDocumentExtension4)document).getDefaultLineDelimiter(); String lineDelimiter= null; try { lineDelimiter= document.getLineDelimiter(0); } catch (BadLocationException x) { x.printStackTrace(); } if (lineDelimiter != null) return lineDelimiter; String sysLineDelimiter= System.getProperty("line.separator"); String[] delimiters= document.getLegalLineDelimiters(); Assert.isTrue(delimiters.length > 0); for (int i= 0; i < delimiters.length; i++) { if (delimiters[i].equals(sysLineDelimiter)) { lineDelimiter= sysLineDelimiter; break; } } if (lineDelimiter == null) lineDelimiter= delimiters[0]; return lineDelimiter; }
protected final String getEol() { IDocument document = getDocument(); if (eol == null) { try { if (document instanceof IDocumentExtension4) { eol = ((IDocumentExtension4)document).getDefaultLineDelimiter(); } else { eol = document.getLineDelimiter(0); } } catch (BadLocationException e) { } } return eol; }
private void setEolChars(IDocument document) { try { if (document instanceof IDocumentExtension4) { eol = ((IDocumentExtension4)document).getDefaultLineDelimiter(); } else { eol = document.getLineDelimiter(0); } int eolLen = eol.length(); eolcp = new int[eolLen]; for (int i=0; i<eolLen; i++) { eolcp[i] = eol.codePointAt(i); } } catch (BadLocationException e) { } }
public static final String getEol(IDocument document) { String eol = "\n"; //$NON-NLS-1$ try { if (document instanceof IDocumentExtension4) { eol = ((IDocumentExtension4)document).getDefaultLineDelimiter(); } else { eol = document.getLineDelimiter(0); } } catch (BadLocationException e) { } return eol; }
@Override public void onSave(BaseEditor edit, IProgressMonitor monitor) { IEditorInput editorInput = edit.getEditorInput(); if (editorInput != null) { IFile file = editorInput.getAdapter(IFile.class); if (file != null) { IDocument document = edit.getDocument(); if (document != null) { fileToSavedTime.put(file, new Tuple3<Long, Long, WeakReference<IDocument>>( ((IDocumentExtension4) document).getModificationStamp(), file.getModificationStamp(), new WeakReference<>(document))); } } } }
public static boolean hasDocumentChanged(IResource resource, IDocument document) { Tuple3<Long, Long, WeakReference<IDocument>> tuple = fileToSavedTime.get(resource); if (tuple == null) { return false; } IDocument cachedDoc = tuple.o3.get(); if (cachedDoc == document) { if (((IDocumentExtension4) document).getModificationStamp() == tuple.o1) { return false; } return true; } return false; }
private static String getCurrentSelectionCacheKey(BaseEditor pyEdit) { IDocument doc = pyEdit.getDocument(); int length = doc.getLength(); String key = Integer.toString(length); if (doc instanceof IDocumentExtension4) { IDocumentExtension4 document = (IDocumentExtension4) doc; long modificationStamp = document.getModificationStamp(); key += " - " + modificationStamp; } return key; }
/** * Stop a rewrite session */ public static void endWrite(IDocument doc, DocumentRewriteSession session) { if (doc instanceof IDocumentExtension4 && session != null) { IDocumentExtension4 d = (IDocumentExtension4) doc; d.stopRewriteSession(session); } }
/** * Starts a rewrite session (keep things in a single undo/redo) */ public static DocumentRewriteSession startWrite(IDocument doc) { if (doc instanceof IDocumentExtension4) { IDocumentExtension4 d = (IDocumentExtension4) doc; return d.startRewriteSession(DocumentRewriteSessionType.UNRESTRICTED); } return null; }
public void checkModificationStamp(RefactoringStatus status, long stampToMatch) { if (fKind == DOCUMENT) { if (stampToMatch != IDocumentExtension4.UNKNOWN_MODIFICATION_STAMP && fModificationStamp != stampToMatch) { status.addFatalError(StringUtils.format("Resource %s has modifications", fResource.getFullPath())); } } else { if (stampToMatch != IResource.NULL_STAMP && fModificationStamp != stampToMatch) { status.addFatalError(StringUtils.format("Resource %s has modifications", fResource.getFullPath())); } } }