Java Code Examples for com.intellij.openapi.editor.Document#getModificationStamp()

The following examples show how to use com.intellij.openapi.editor.Document#getModificationStamp() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FileDocumentManagerImplTest.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void testContentChanged_DoNotReloadChangedDocument() throws Exception {
  final VirtualFile file = createFile();
  final Document document = myDocumentManager.getDocument(file);
  assertNotNull(file.toString(), document);
  WriteCommandAction.runWriteCommandAction(myProject, new Runnable() {
    @Override
    public void run() {
      document.insertString(0, "old ");
    }
  });

  myReloadFromDisk = Boolean.FALSE;
  long oldDocumentStamp = document.getModificationStamp();

  file.setBinaryContent("xxx".getBytes(CharsetToolkit.UTF8_CHARSET));

  assertEquals("old test", document.getText());
  assertEquals(oldDocumentStamp, document.getModificationStamp());
}
 
Example 2
Source File: IdeaGateway.java    From consulo with Apache License 2.0 6 votes vote down vote up
@javax.annotation.Nullable
public Pair<StoredContent, Long> acquireAndUpdateActualContent(@Nonnull VirtualFile f, @Nullable Document d) {
  ContentAndTimestamps contentAndStamp = f.getUserData(SAVED_DOCUMENT_CONTENT_AND_STAMP_KEY);
  if (contentAndStamp == null) {
    if (d != null) saveDocumentContent(f, d);
    return Pair.create(StoredContent.acquireContent(f), f.getTimeStamp());
  }

  // if no need to save current document content when simply return and clear stored one
  if (d == null) {
    f.putUserData(SAVED_DOCUMENT_CONTENT_AND_STAMP_KEY, null);
    return Pair.create(contentAndStamp.content, contentAndStamp.registeredTimestamp);
  }

  // if the stored content equals the current one, do not store it and return null
  if (d.getModificationStamp() == contentAndStamp.documentModificationStamp) return null;

  // is current content has been changed, store it and return the previous one
  saveDocumentContent(f, d);
  return Pair.create(contentAndStamp.content, contentAndStamp.registeredTimestamp);
}
 
Example 3
Source File: IdeaGateway.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
public Pair<StoredContent, Long> acquireAndClearCurrentContent(@Nonnull VirtualFile f, @Nullable Document d) {
  ContentAndTimestamps contentAndStamp = f.getUserData(SAVED_DOCUMENT_CONTENT_AND_STAMP_KEY);
  f.putUserData(SAVED_DOCUMENT_CONTENT_AND_STAMP_KEY, null);

  if (d != null && contentAndStamp != null) {
    // if previously stored content was not changed, return it
    if (d.getModificationStamp() == contentAndStamp.documentModificationStamp) {
      return Pair.create(contentAndStamp.content, contentAndStamp.registeredTimestamp);
    }
  }

  // release previously stored
  if (contentAndStamp != null) {
    contentAndStamp.content.release();
  }

  // take document's content if any
  if (d != null) {
    return Pair.create(StoredContent.acquireContent(bytesFromDocument(d)), Clock.getTime());
  }

  return Pair.create(StoredContent.acquireContent(f), f.getTimeStamp());
}
 
Example 4
Source File: FormattingProgressTask.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
  FORMATTING_CANCELLED_FLAG.set(true);
  VirtualFile file = myFile.get();
  Document document = myDocument.get();
  if (file == null || document == null || myDocumentModificationStampBefore < 0) {
    return;
  }
  FileEditor editor = FileEditorManager.getInstance(myProject).getSelectedEditor(file);
  if (editor == null) {
    return;
  }

  UndoManager manager = UndoManager.getInstance(myProject);
  while (manager.isUndoAvailable(editor) && document.getModificationStamp() != myDocumentModificationStampBefore) {
    manager.undo(editor);
  }
}
 
Example 5
Source File: DefaultHighlightInfoProcessor.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void highlightsOutsideVisiblePartAreProduced(@Nonnull final HighlightingSession session,
                                                    @Nullable Editor editor,
                                                    @Nonnull final List<? extends HighlightInfo> infos,
                                                    @Nonnull final TextRange priorityRange,
                                                    @Nonnull final TextRange restrictedRange, final int groupId) {
  final PsiFile psiFile = session.getPsiFile();
  final Project project = psiFile.getProject();
  final Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile);
  if (document == null) return;
  final long modificationStamp = document.getModificationStamp();
  ((HighlightingSessionImpl)session).applyInEDT(() -> {
    if (project.isDisposed() || modificationStamp != document.getModificationStamp()) return;

    EditorColorsScheme scheme = session.getColorsScheme();

    UpdateHighlightersUtil
            .setHighlightersOutsideRange(project, document, psiFile, infos, scheme, restrictedRange.getStartOffset(), restrictedRange.getEndOffset(), ProperTextRange.create(priorityRange), groupId);
    if (editor != null) {
      repaintErrorStripeAndIcon(editor, project);
    }
  });
}
 
Example 6
Source File: BsCompilerImpl.java    From reasonml-idea-plugin with MIT License 5 votes vote down vote up
public void refmtCount(@NotNull VirtualFile sourceFile, boolean isInterface, @NotNull String format, @NotNull Document document, final int retries) {
    if (!sourceFile.exists()) {
        return;
    }

    if (ReasonSettings.getInstance(m_project).isEnabled()) {
        long before = document.getModificationStamp();

        RefmtProcess refmt = RefmtProcess.getInstance(m_project);
        String oldText = document.getText();
        if (!oldText.isEmpty()) {
            String newText = refmt.run(sourceFile, isInterface, format, oldText);
            if (!newText.isEmpty() && !oldText.equals(newText)) { // additional protection
                ApplicationManager.getApplication().invokeLater(() -> {
                    long after = document.getModificationStamp();
                    if (after > before) {
                        // Document has changed, redo refmt one time
                        if (retries < 2) {
                            refmtCount(sourceFile, isInterface, format, document, retries + 1);
                        }
                    } else {
                        CommandProcessor.getInstance().executeCommand(m_project, () -> {
                            WriteAction.run(() -> {
                                document.setText(newText);
                                FileDocumentManager.getInstance().saveDocument(document);
                            });
                            sourceFile.putUserData(UndoConstants.FORCE_RECORD_UNDO, null);
                        }, "reason.refmt", "CodeFormatGroup", document);
                    }
                });
            }
        }
    }
}
 
Example 7
Source File: FileDocumentManagerImplTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void testContentChanged_ignoreEventsFromSelfOnSave() throws Exception {
  final VirtualFile file = new MockVirtualFile("test.txt", "test\rtest") {
    @Nonnull
    @Override
    public OutputStream getOutputStream(final Object requestor, final long newModificationStamp, long newTimeStamp) throws IOException {
      final VirtualFile self = this;
      return new ByteArrayOutputStream() {
        @Override
        public void close() throws IOException {
          super.close();
          long oldStamp = getModificationStamp();
          setModificationStamp(newModificationStamp);
          setText(toString());
          myDocumentManager.contentsChanged(new VFileContentChangeEvent(requestor, self, oldStamp, getModificationStamp(), false));
        }
      };
    }
  };
  final Document document = myDocumentManager.getDocument(file);
  assertNotNull(file.toString(), document);
  WriteCommandAction.runWriteCommandAction(myProject, new Runnable() {
    @Override
    public void run() {
      document.insertString(0, "xxx");
    }
  });

  final long stamp = document.getModificationStamp();

  myDocumentManager.saveAllDocuments();
  assertEquals(stamp, document.getModificationStamp());
}
 
Example 8
Source File: FileDocumentManagerImplTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void testContentChanged_doNotReloadChangedDocumentOnSave() throws Exception {
  final MockVirtualFile file = new MockVirtualFile("test.txt", "test") {
    @Override
    public void refresh(boolean asynchronous, boolean recursive, Runnable postRunnable) {
      long oldStamp = getModificationStamp();
      setModificationStamp(LocalTimeCounter.currentTime());
      myDocumentManager.contentsChanged(new VFileContentChangeEvent(null, this, oldStamp, getModificationStamp(), true));
    }
  };

  myReloadFromDisk = Boolean.FALSE;
  final Document document = myDocumentManager.getDocument(file);
  assertNotNull(file.toString(), document);
  WriteCommandAction.runWriteCommandAction(myProject, new Runnable() {
    @Override
    public void run() {
      document.insertString(0, "old ");
    }
  });

  long documentStamp = document.getModificationStamp();

  file.setContent(null, "xxx", false);

  myDocumentManager.saveAllDocuments();

  assertEquals("old test", document.getText());
  assertEquals(file.getModificationStamp(), document.getModificationStamp());
  assertTrue(Arrays.equals("old test".getBytes("UTF-8"), file.contentsToByteArray()));
  assertEquals(documentStamp, document.getModificationStamp());
}
 
Example 9
Source File: TextEditorHighlightingPass.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected TextEditorHighlightingPass(@Nonnull final Project project, @Nullable final Document document, boolean runIntentionPassAfter) {
  myDocument = document;
  myProject = project;
  myRunIntentionPassAfter = runIntentionPassAfter;
  myInitialDocStamp = document == null ? 0 : document.getModificationStamp();
  myInitialPsiStamp = PsiModificationTracker.SERVICE.getInstance(myProject).getModificationCount();
}
 
Example 10
Source File: MemoryDiskConflictResolver.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void processConflicts() {
  List<VirtualFile> conflicts = new ArrayList<>(myConflicts);
  myConflicts.clear();

  for (VirtualFile file : conflicts) {
    Document document = FileDocumentManager.getInstance().getCachedDocument(file);
    if (document != null && file.getModificationStamp() != document.getModificationStamp() && askReloadFromDisk(file, document)) {
      FileDocumentManager.getInstance().reloadFromDisk(document);
    }
  }
  myConflictAppeared = null;
}
 
Example 11
Source File: FileDocumentManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void contentsChanged(VFileContentChangeEvent event) {
  VirtualFile virtualFile = event.getFile();
  Document document = getCachedDocument(virtualFile);

  if (event.isFromSave()) return;

  if (document == null || isBinaryWithDecompiler(virtualFile)) {
    myMultiCaster.fileWithNoDocumentChanged(virtualFile); // This will generate PSI event at FileManagerImpl
  }

  if (document != null && (document.getModificationStamp() == event.getOldModificationStamp() || !isDocumentUnsaved(document))) {
    reloadFromDisk(document);
  }
}
 
Example 12
Source File: DefaultHighlightInfoProcessor.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void highlightsInsideVisiblePartAreProduced(@Nonnull final HighlightingSession session,
                                                   @Nullable Editor editor,
                                                   @Nonnull final List<? extends HighlightInfo> infos,
                                                   @Nonnull TextRange priorityRange,
                                                   @Nonnull TextRange restrictRange,
                                                   final int groupId) {
  final PsiFile psiFile = session.getPsiFile();
  final Project project = psiFile.getProject();
  final Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile);
  if (document == null) return;
  final long modificationStamp = document.getModificationStamp();
  final TextRange priorityIntersection = priorityRange.intersection(restrictRange);
  List<? extends HighlightInfo> infoCopy = new ArrayList<>(infos);
  ((HighlightingSessionImpl)session).applyInEDT(() -> {
    if (modificationStamp != document.getModificationStamp()) return;
    if (priorityIntersection != null) {
      MarkupModel markupModel = DocumentMarkupModel.forDocument(document, project, true);

      EditorColorsScheme scheme = session.getColorsScheme();
      UpdateHighlightersUtil.setHighlightersInRange(project, document, priorityIntersection, scheme, infoCopy, (MarkupModelEx)markupModel, groupId);
    }
    if (editor != null && !editor.isDisposed()) {
      // usability: show auto import popup as soon as possible
      if (!DumbService.isDumb(project)) {
        ShowAutoImportPassFactory siFactory = TextEditorHighlightingPassFactory.EP_NAME.findExtensionOrFail(project, ShowAutoImportPassFactory.class);
        TextEditorHighlightingPass highlightingPass = siFactory.createHighlightingPass(psiFile, editor);
        if (highlightingPass != null) {
          highlightingPass.doApplyInformationToEditor();
        }
      }

      repaintErrorStripeAndIcon(editor, project);
    }
  });
}
 
Example 13
Source File: FindResultUsageInfo.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isValid() {
  if (!super.isValid()) return false;

  Document document = PsiDocumentManager.getInstance(getProject()).getDocument(getPsiFile());
  if (document == null) {
    myCachedResult = null;
    return false;
  }

  Boolean cachedResult = myCachedResult;
  if (document.getModificationStamp() == myTimestamp && cachedResult != null) {
    return cachedResult;
  }
  myTimestamp = document.getModificationStamp();

  Segment segment = getSegment();
  if (segment == null) {
    myCachedResult = false;
    return false;
  }

  VirtualFile file = getPsiFile().getVirtualFile();

  Segment searchOffset;
  if (myAnchor != null) {
    searchOffset = myAnchor.getRange();
    if (searchOffset == null) {
      myCachedResult = false;
      return false;
    }
  }
  else {
    searchOffset = segment;
  }

  int offset = searchOffset.getStartOffset();
  Long data = myFindModel.getUserData(ourDocumentTimestampKey);
  if (data == null || data != myTimestamp) {
    data = myTimestamp;
    FindManagerImpl.clearPreviousFindData(myFindModel);
  }
  myFindModel.putUserData(ourDocumentTimestampKey, data);
  FindResult result;
  do {
    result = myFindManager.findString(document.getCharsSequence(), offset, myFindModel, file);
    offset = result.getEndOffset() == offset ? offset + 1 : result.getEndOffset();
    if (!result.isStringFound()) {
      myCachedResult = false;
      return false;
    }
  } while (result.getStartOffset() < segment.getStartOffset());

  boolean ret = segment.getStartOffset() == result.getStartOffset() && segment.getEndOffset() == result.getEndOffset();
  myCachedResult = ret;
  return ret;
}
 
Example 14
Source File: EnterAfterUnmatchedBraceHandler.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * Formats the code block between caret and inserted braces.
 *
 * @param file                target PSI file
 * @param document            target document
 * @param caretOffset         target caret offset
 * @param rBracesInsertOffset target position to insert
 * @param generatedRBraces    string of '}' to insert
 */
protected void formatCodeFragmentBetweenBraces(@Nonnull PsiFile file,
                                               @Nonnull Document document,
                                               int caretOffset,
                                               int rBracesInsertOffset,
                                               String generatedRBraces) {
  Project project = file.getProject();
  long stamp = document.getModificationStamp();
  boolean closingBraceIndentAdjusted;
  try {
    PsiDocumentManager.getInstance(project).commitDocument(document);
    CodeStyleManager.getInstance(project).adjustLineIndent(file, new TextRange(caretOffset, rBracesInsertOffset + 2));
  }
  catch (IncorrectOperationException e) {
    LOG.error(e);
  }
  finally {
    closingBraceIndentAdjusted = stamp != document.getModificationStamp();
    // do you remember that we insert the '\n'? here we take it back!
    document.deleteString(caretOffset, caretOffset + 1);
  }

  // There is a possible case that formatter was unable to adjust line indent for the closing brace (that is the case for plain text
  // document for example). Hence, we're trying to do the manually.
  if (!closingBraceIndentAdjusted) {
    int line = document.getLineNumber(rBracesInsertOffset);
    StringBuilder buffer = new StringBuilder();
    int start = document.getLineStartOffset(line);
    int end = document.getLineEndOffset(line);
    final CharSequence text = document.getCharsSequence();
    for (int i = start; i < end; i++) {
      char c = text.charAt(i);
      if (c != ' ' && c != '\t') {
        break;
      }
      else {
        buffer.append(c);
      }
    }
    if (buffer.length() > 0) {
      document.insertString(rBracesInsertOffset + 1, buffer);
    }
  }
}
 
Example 15
Source File: DaemonCodeAnalyzerImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isErrorAnalyzingFinished(@Nonnull PsiFile file) {
  if (myDisposed) return false;
  Document document = myPsiDocumentManager.getCachedDocument(file);
  return document != null && document.getModificationStamp() == file.getViewProvider().getModificationStamp() && myFileStatusMap.getFileDirtyScope(document, Pass.UPDATE_ALL) == null;
}
 
Example 16
Source File: DaemonCodeAnalyzerImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
boolean isAllAnalysisFinished(@Nonnull PsiFile file) {
  if (myDisposed) return false;
  Document document = myPsiDocumentManager.getCachedDocument(file);
  return document != null && document.getModificationStamp() == file.getViewProvider().getModificationStamp() && myFileStatusMap.allDirtyScopesAreNull(document);
}
 
Example 17
Source File: StubTreeLoader.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
public RuntimeException stubTreeAndIndexDoNotMatch(@Nullable ObjectStubTree stubTree, @Nonnull PsiFileWithStubSupport psiFile, @Nullable Throwable cause) {
  VirtualFile file = psiFile.getViewProvider().getVirtualFile();
  StubTree stubTreeFromIndex = (StubTree)readFromVFile(psiFile.getProject(), file);
  boolean compiled = psiFile instanceof PsiCompiledElement;
  Document document = compiled ? null : FileDocumentManager.getInstance().getDocument(file);
  IndexingStampInfo indexingStampInfo = getIndexingStampInfo(file);
  boolean upToDate = indexingStampInfo != null && indexingStampInfo.isUpToDate(document, file, psiFile);

  boolean canBePrebuilt = isPrebuilt(psiFile.getVirtualFile());

  String msg = "PSI and index do not match.\nPlease report the problem to JetBrains with the files attached\n";

  if (canBePrebuilt) {
    msg += "This stub can have pre-built origin\n";
  }

  if (upToDate) {
    msg += "INDEXED VERSION IS THE CURRENT ONE";
  }

  msg += " file=" + psiFile;
  msg += ", file.class=" + psiFile.getClass();
  msg += ", file.lang=" + psiFile.getLanguage();
  msg += ", modStamp=" + psiFile.getModificationStamp();

  if (!compiled) {
    String text = psiFile.getText();
    PsiFile fromText = PsiFileFactory.getInstance(psiFile.getProject()).createFileFromText(psiFile.getName(), psiFile.getFileType(), text);
    if (fromText.getLanguage().equals(psiFile.getLanguage())) {
      boolean consistent = DebugUtil.psiToString(psiFile, true).equals(DebugUtil.psiToString(fromText, true));
      if (consistent) {
        msg += "\n tree consistent";
      }
      else {
        msg += "\n AST INCONSISTENT, perhaps after incremental reparse; " + fromText;
      }
    }
  }

  if (stubTree != null) {
    msg += "\n stub debugInfo=" + stubTree.getDebugInfo();
  }

  msg += "\nlatestIndexedStub=" + stubTreeFromIndex;
  if (stubTreeFromIndex != null) {
    if (stubTree != null) {
      msg += "\n   same size=" + (stubTree.getPlainList().size() == stubTreeFromIndex.getPlainList().size());
    }
    msg += "\n   debugInfo=" + stubTreeFromIndex.getDebugInfo();
  }

  FileViewProvider viewProvider = psiFile.getViewProvider();
  msg += "\n viewProvider=" + viewProvider;
  msg += "\n viewProvider stamp: " + viewProvider.getModificationStamp();

  msg += "; file stamp: " + file.getModificationStamp();
  msg += "; file modCount: " + file.getModificationCount();
  msg += "; file length: " + file.getLength();

  if (document != null) {
    msg += "\n doc saved: " + !FileDocumentManager.getInstance().isDocumentUnsaved(document);
    msg += "; doc stamp: " + document.getModificationStamp();
    msg += "; doc size: " + document.getTextLength();
    msg += "; committed: " + PsiDocumentManager.getInstance(psiFile.getProject()).isCommitted(document);
  }

  msg += "\nindexing info: " + indexingStampInfo;

  Attachment[] attachments = createAttachments(stubTree, psiFile, file, stubTreeFromIndex);

  // separate methods and separate exception classes for EA to treat these situations differently
  return hasPsiInManyProjects(file)
         ? handleManyProjectsMismatch(msg, attachments, cause)
         : upToDate ? handleUpToDateMismatch(msg, attachments, cause) : new RuntimeExceptionWithAttachments(msg, cause, attachments);
}
 
Example 18
Source File: FileDocumentManagerImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isFileModified(@Nonnull VirtualFile file) {
  final Document doc = getCachedDocument(file);
  return doc != null && isDocumentUnsaved(doc) && doc.getModificationStamp() != file.getModificationStamp();
}
 
Example 19
Source File: MockDocumentEvent.java    From consulo with Apache License 2.0 4 votes vote down vote up
public MockDocumentEvent(@Nonnull Document document, int offset) {
  super(document);
  myOffset = offset;
  myTimestamp = document.getModificationStamp();
}
 
Example 20
Source File: MockPsiDocumentManager.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public long getLastCommittedStamp(@Nonnull Document document) {
  return document.getModificationStamp();
}