com.intellij.openapi.editor.event.DocumentEvent Java Examples

The following examples show how to use com.intellij.openapi.editor.event.DocumentEvent. 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: ExternalSystemAutoImporter.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void documentChanged(DocumentEvent event) {
  Document document = event.getDocument();
  FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance();
  VirtualFile file = fileDocumentManager.getFile(document);
  if (file == null) {
    return;
  }

  String path = ExternalSystemApiUtil.getLocalFileSystemPath(file);
  for (MyEntry entry : myAutoImportAware) {
    if (entry.aware.getAffectedExternalProjectPath(path, myProject) != null) {
      // Document save triggers VFS event but FileDocumentManager might be registered after the current listener, that's why
      // call to 'saveDocument()' might not produce the desired effect. That's why we reschedule document save if necessary.
      scheduleDocumentSave(document);
      return;
    }
  } 
}
 
Example #2
Source File: InputPanel.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void createManualInputPreviewEditor(final PreviewState previewState) {
	final EditorFactory factory = EditorFactory.getInstance();
	Document doc = factory.createDocument("");
	doc.addDocumentListener(
		new DocumentAdapter() {
			@Override
			public void documentChanged(DocumentEvent e) {
				previewState.manualInputText = e.getDocument().getCharsSequence();
			}
		}
	                       );

	Editor editor = createPreviewEditor(previewState.grammarFile, doc, false);
	setEditorComponent(editor.getComponent()); // do before setting state
	previewState.setInputEditor(editor);

	// Set text last to trigger change events
	ApplicationManager.getApplication().runWriteAction(() -> doc.setText(previewState.manualInputText));
}
 
Example #3
Source File: RangeMarkerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public final void documentChanged(@Nonnull DocumentEvent e) {
  int oldStart = intervalStart();
  int oldEnd = intervalEnd();
  int docLength = getDocument().getTextLength();
  if (!isValid()) {
    LOG.error("Invalid range marker " + (isGreedyToLeft() ? "[" : "(") + oldStart + ", " + oldEnd + (isGreedyToRight() ? "]" : ")") +
              ". Event = " + e + ". Doc length=" + docLength + "; " + getClass());
    return;
  }
  if (intervalStart() > intervalEnd() || intervalStart() < 0 || intervalEnd() > docLength - e.getNewLength() + e.getOldLength()) {
    LOG.error("RangeMarker" + (isGreedyToLeft() ? "[" : "(") + oldStart + ", " + oldEnd + (isGreedyToRight() ? "]" : ")") +
              " is invalid before update. Event = " + e + ". Doc length=" + docLength + "; " + getClass());
    invalidate(e);
    return;
  }
  changedUpdateImpl(e);
  if (isValid() && (intervalStart() > intervalEnd() || intervalStart() < 0 || intervalEnd() > docLength)) {
    LOG.error("Update failed. Event = " + e + ". " +
              "old doc length=" + docLength + "; real doc length = " + getDocument().getTextLength() +
              "; " + getClass() + "." +
              " After update: '" + this + "'");
    invalidate(e);
  }
}
 
Example #4
Source File: TabOutScopesTrackerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeDocumentChange(@Nonnull DocumentEvent event) {
  List<RangeMarker> scopes = getCurrentScopes(false);
  if (scopes == null) return;
  int caretOffset = myEditor.getCaretModel().getOffset();
  int changeStart = event.getOffset();
  int changeEnd = event.getOffset() + event.getOldLength();
  for (Iterator<RangeMarker> it = scopes.iterator(); it.hasNext(); ) {
    RangeMarker scope = it.next();
    // We don't reset scope if the change is completely inside our scope, or if caret is inside, but the change is outside
    if ((changeStart < scope.getStartOffset() || changeEnd > scope.getEndOffset()) &&
        (caretOffset < scope.getStartOffset() || caretOffset > scope.getEndOffset() || (changeEnd >= scope.getStartOffset() && changeStart <= scope.getEndOffset()))) {
      it.remove();
    }
  }
}
 
Example #5
Source File: RangeMarkerTree.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void updateMarkersOnChange(@Nonnull DocumentEvent e) {
  try {
    l.writeLock().lock();
    if (size() == 0) return;
    checkMax(true);

    incModCount();

    List<IntervalNode<T>> affected = new SmartList<>();
    collectAffectedMarkersAndShiftSubtrees(getRoot(), e, affected);
    checkMax(false);

    if (!affected.isEmpty()) {
      updateAffectedNodes(e, affected);
    }
    checkMax(true);

    IntervalNode<T> root = getRoot();
    assert root == null || root.maxEnd + root.delta <= e.getDocument().getTextLength();
  }
  finally {
    l.writeLock().unlock();
  }
}
 
Example #6
Source File: PersistentRangeHighlighterImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
protected void changedUpdateImpl(@Nonnull DocumentEvent e) {
  // todo Denis Zhdanov
  DocumentEventImpl event = (DocumentEventImpl)e;
  final boolean shouldTranslateViaDiff = isValid() && PersistentRangeMarkerUtil.shouldTranslateViaDiff(event, getStartOffset(), getEndOffset());
  boolean wasTranslatedViaDiff = shouldTranslateViaDiff;
  if (shouldTranslateViaDiff) {
    wasTranslatedViaDiff = translatedViaDiff(e, event);
  }
  if (!wasTranslatedViaDiff) {
    super.changedUpdateImpl(e);
    if (isValid()) {
      myLine = getDocument().getLineNumber(getStartOffset());
      int endLine = getDocument().getLineNumber(getEndOffset());
      if (endLine != myLine) {
        setIntervalEnd(getDocument().getLineEndOffset(myLine));
      }
    }
  }
  if (isValid() && getTargetArea() == HighlighterTargetArea.LINES_IN_RANGE) {
    setIntervalStart(DocumentUtil.getFirstNonSpaceCharOffset(getDocument(), myLine));
    setIntervalEnd(getDocument().getLineEndOffset(myLine));
  }
}
 
Example #7
Source File: DesktopCaretImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
protected void changedUpdateImpl(@Nonnull DocumentEvent e) {
  super.changedUpdateImpl(e);
  if (isValid()) {
    int startOffset = intervalStart();
    int endOffset = intervalEnd();
    if (DocumentUtil.isInsideSurrogatePair(getDocument(), startOffset)) setIntervalStart(startOffset - 1);
    if (DocumentUtil.isInsideSurrogatePair(getDocument(), endOffset)) setIntervalStart(endOffset - 1);
  }
  if (endVirtualOffset > 0 && isValid()) {
    Document document = e.getDocument();
    int startAfter = intervalStart();
    int endAfter = intervalEnd();
    if (!DocumentUtil.isAtLineEnd(endAfter, document) || document.getLineNumber(startAfter) != document.getLineNumber(endAfter)) {
      resetVirtualSelection();
    }
  }
}
 
Example #8
Source File: DocumentChangesCollector.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void documentChanged(DocumentEvent event) {
  if (!myCollectChanges) {
    return;
  }

  // The general algorithm is as follows:
  //   1. Drop or cut stored change ranges for removed range if any;
  //   2. Update offsets of all ranges that lays after the last change range identified by the given document change event;
  //   3. Merge added range with registered changes if any;
  //   4. Merge all adjacent ranges if any;
  StringBuilder oldText = new StringBuilder(event.getOldFragment());

  cutChangesIfNecessary(event, oldText);
  updateChanges(event, oldText);
  mergeChangesIfNecessary(event);
}
 
Example #9
Source File: RangeMarkerTest.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void testDocSynchronizerPrefersLineBoundaryChanges() throws Exception {
  String text = "import java.awt.List;\n" +
                "[import java.util.ArrayList;\n]" +
                "import java.util.HashMap;\n" +
                "import java.util.Map;";
  RangeMarker marker = createMarker(text);
  synchronizer.startTransaction(getProject(), document, psiFile);

  String newText = StringUtil.replaceSubstring(document.getText(), TextRange.create(marker), "");
  synchronizer.replaceString(document, 0, document.getTextLength(), newText);

  final List<DocumentEvent> events = new ArrayList<DocumentEvent>();
  document.addDocumentListener(new DocumentAdapter() {
    @Override
    public void documentChanged(DocumentEvent e) {
      events.add(e);
    }
  });
  synchronizer.commitTransaction(document);

  assertEquals(newText, document.getText());
  DocumentEvent event = assertOneElement(events);
  assertEquals("DocumentEventImpl[myOffset=22, myOldLength=28, myNewLength=0, myOldString='import java.util.ArrayList;\n', myNewString=''].", event.toString());
}
 
Example #10
Source File: DocumentUndoProvider.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeDocumentChange(@Nonnull DocumentEvent e) {
  Document document = e.getDocument();
  if (!shouldProcess(document)) {
    return;
  }

  handleBeforeDocumentChange(getUndoManager(null), document);

  ProjectManager projectManager = ProjectManager.getInstance();
  if (projectManager != null) {
    for (Project project : projectManager.getOpenProjects()) {
      handleBeforeDocumentChange(getUndoManager(project), document);
    }
  }
}
 
Example #11
Source File: QuickEditHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void commitToOriginal(final DocumentEvent e) {
  VirtualFile origVirtualFile = PsiUtilCore.getVirtualFile(myNewFile.getContext());
  myCommittingToOriginal = true;
  try {
    if (origVirtualFile == null || !ReadonlyStatusHandler.getInstance(myProject).ensureFilesWritable(origVirtualFile).hasReadonlyFiles()) {
      PostprocessReformattingAspect.getInstance(myProject).disablePostprocessFormattingInside(new Runnable() {
        @Override
        public void run() {
          if (myAltFullRange != null) {
            altCommitToOriginal(e);
            return;
          }
          commitToOriginalInner();
        }
      });
      PsiDocumentManager.getInstance(myProject).doPostponedOperationsAndUnblockDocument(myOrigDocument);
    }
  }
  finally {
    myCommittingToOriginal = false;
  }
}
 
Example #12
Source File: DocumentChangesCollector.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void mergeChangesIfNecessary(DocumentEvent event) {
  // There is a possible case that we had more than one scattered change (e.g. (3; 5) and (8; 10)) and current document change affects
  // both of them (e.g. remove all symbols from offset (4; 9)). We have two changes then: (3; 4) and (4; 5) and want to merge them
  // into a single one.
  if (myChanges.size() < 2) {
    return;
  }
  TextChangeImpl next = myChanges.get(myChanges.size() - 1);
  for (int i = myChanges.size() - 2; i >= 0; i--) {
    TextChangeImpl current = myChanges.get(i);
    if (current.getEnd() < event.getOffset()) {
      // Assuming that change ranges are always kept at normalized form.
      break;
    }
    if (current.getEnd() == next.getStart()) {
      myChanges.set(i, next = new TextChangeImpl(current.getText().toString() + next.getText(), current.getStart(), next.getEnd()));
      myChanges.remove(i + 1);
    }
    else {
      next = current;
    }
  }
}
 
Example #13
Source File: PersistentRangeMarkerUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Answers if document region identified by the given range marker should be translated via diff algorithm on document change
 * identified by the given event.
 *
 * @param e             event that describes document change
 * @param rangeStart    target range marker start, for which update strategy should be selected
 * @param rangeEnd      target range marker end
 * @return              {@code true} if target document range referenced by the given range marker should be translated via
 *                      diff algorithm; {@code false} otherwise
 */
static boolean shouldTranslateViaDiff(@Nonnull DocumentEvent e, int rangeStart, int rangeEnd) {
  if (e.isWholeTextReplaced()) {
    // Perform translation if the whole text is replaced.
    return true;
  }

  if (e.getOffset() >= rangeEnd || e.getOffset() + e.getOldLength() <= rangeStart) {
    // Don't perform complex processing if the change doesn't affect target range.
    return false;
  }

  // Perform complex processing only if significant document part is updated.
  return (Math.max(e.getNewLength(), e.getOldLength()) * 1.0) / e.getDocument().getTextLength() >= 0.8;
}
 
Example #14
Source File: LocalClosedEditorModificationHandler.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Adjusts the annotations for the resource represented by the changed document if it is not
 * currently open in an editor. If it is currently open in an editor, this will be done
 * automatically by Intellij.
 *
 * @param event the event to react to
 * @see DocumentListener#beforeDocumentChange(DocumentEvent)
 */
private void cleanUpAnnotations(@NotNull DocumentEvent event) {
  Document document = event.getDocument();

  IFile file = getFile(document);

  if (file == null) {
    return;
  }

  int offset = event.getOffset();
  String newText = event.getNewFragment().toString();
  String replacedText = event.getOldFragment().toString();

  if (!ProjectAPI.isOpen(project, document)) {

    int replacedTextLength = replacedText.length();
    if (replacedTextLength > 0) {
      annotationManager.moveAnnotationsAfterDeletion(file, offset, offset + replacedTextLength);
    }

    int newTextLength = newText.length();
    if (newTextLength > 0) {
      annotationManager.moveAnnotationsAfterAddition(file, offset, offset + newTextLength);
    }
  }
}
 
Example #15
Source File: EncodingManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
public EncodingManagerImpl() {
  ApplicationManager.getApplication().getMessageBus().connect().subscribe(AppLifecycleListener.TOPIC, new AppLifecycleListener() {
    @Override
    public void appClosing() {
      // should call before dispose in write action
      // prevent any further re-detection and wait for the queue to clear
      myDisposed.set(true);
      clearDocumentQueue();
    }
  });

  EditorFactory editorFactory = EditorFactory.getInstance();
  editorFactory.getEventMulticaster().addDocumentListener(new DocumentListener() {
    @Override
    public void documentChanged(@Nonnull DocumentEvent e) {
      Document document = e.getDocument();
      if (isEditorOpenedFor(document)) {
        queueUpdateEncodingFromContent(document);
      }
    }
  }, this);
  editorFactory.addEditorFactoryListener(new EditorFactoryListener() {
    @Override
    public void editorCreated(@Nonnull EditorFactoryEvent event) {
      queueUpdateEncodingFromContent(event.getEditor().getDocument());
    }
  }, this);
}
 
Example #16
Source File: SelfElementInfo.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static Segment calcActualRangeAfterDocumentEvents(@Nonnull PsiFile containingFile, @Nonnull Document document, @Nonnull Segment segment, boolean isSegmentGreedy) {
  Project project = containingFile.getProject();
  PsiDocumentManagerBase documentManager = (PsiDocumentManagerBase)PsiDocumentManager.getInstance(project);
  List<DocumentEvent> events = documentManager.getEventsSinceCommit(document);
  if (!events.isEmpty()) {
    SmartPointerManagerImpl pointerManager = (SmartPointerManagerImpl)SmartPointerManager.getInstance(project);
    SmartPointerTracker tracker = pointerManager.getTracker(containingFile.getViewProvider().getVirtualFile());
    if (tracker != null) {
      return tracker.getUpdatedRange(containingFile, segment, isSegmentGreedy, (FrozenDocument)documentManager.getLastCommittedDocument(document), events);
    }
  }
  return null;
}
 
Example #17
Source File: LineStatusTrackerBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeDocumentChange(DocumentEvent e) {
  if (isSuppressed()) return;
  assert myDocument == e.getDocument();

  myLine1 = myDocument.getLineNumber(e.getOffset());
  if (e.getOldLength() == 0) {
    myLine2 = myLine1 + 1;
  }
  else {
    myLine2 = myDocument.getLineNumber(e.getOffset() + e.getOldLength()) + 1;
  }

  myBeforeTotalLines = getLineCount(myDocument);
}
 
Example #18
Source File: MarkerCache.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
TextRange getUpdatedRange(@Nonnull SelfElementInfo info, @Nonnull FrozenDocument frozen, @Nonnull List<? extends DocumentEvent> events) {
  UpdatedRanges struct = getUpdatedMarkers(frozen, events);
  int i = Collections.binarySearch(struct.mySortedInfos, info, INFO_COMPARATOR);
  ManualRangeMarker updated = i >= 0 ? struct.myMarkers[i] : null;
  return updated == null ? null : new UnfairTextRange(updated.getStartOffset(), updated.getEndOffset());
}
 
Example #19
Source File: OffsetTranslator.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
Integer translateOffset(Integer offset) {
  for (DocumentEvent event : myTranslation) {
    offset = translateOffset(offset, event);
    if (offset == null) {
      return null;
    }
  }
  return offset;
}
 
Example #20
Source File: FileStatusManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Inject
public FileStatusManagerImpl(Project project, StartupManager startupManager, @SuppressWarnings("UnusedParameters") DirectoryIndex makeSureIndexIsInitializedFirst) {
  myProject = project;

  project.getMessageBus().connect().subscribe(EditorColorsManager.TOPIC, new EditorColorsListener() {
    @Override
    public void globalSchemeChange(EditorColorsScheme scheme) {
      fileStatusesChanged();
    }
  });

  if (project.isDefault()) return;

  startupManager.registerPreStartupActivity(() -> {
    DocumentAdapter documentListener = new DocumentAdapter() {
      @Override
      public void documentChanged(DocumentEvent event) {
        if (event.getOldLength() == 0 && event.getNewLength() == 0) return;
        VirtualFile file = FileDocumentManager.getInstance().getFile(event.getDocument());
        if (file != null) {
          refreshFileStatusFromDocument(file, event.getDocument());
        }
      }
    };

    final EditorFactory factory = EditorFactory.getInstance();
    if (factory != null) {
      factory.getEventMulticaster().addDocumentListener(documentListener, myProject);
    }
  });
  startupManager.registerPostStartupActivity(new DumbAwareRunnable() {
    @Override
    public void run() {
      fileStatusesChanged();
    }
  });
}
 
Example #21
Source File: StatisticsUpdate.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void trackStatistics(InsertionContext context) {
  if (ourPendingUpdate != this) {
    return;
  }

  if (!context.getOffsetMap().containsOffset(CompletionInitializationContext.START_OFFSET)) {
    return;
  }

  final Document document = context.getDocument();
  int startOffset = context.getStartOffset();
  int tailOffset = context.getEditor().getCaretModel().getOffset();
  if (startOffset < 0 || tailOffset <= startOffset) {
    return;
  }

  final RangeMarker marker = document.createRangeMarker(startOffset, tailOffset);
  final DocumentAdapter listener = new DocumentAdapter() {
    @Override
    public void beforeDocumentChange(DocumentEvent e) {
      if (!marker.isValid() || e.getOffset() > marker.getStartOffset() && e.getOffset() < marker.getEndOffset()) {
        cancelLastCompletionStatisticsUpdate();
      }
    }
  };

  ourStatsAlarm.addRequest(() -> {
    if (ourPendingUpdate == this) {
      applyLastCompletionStatisticsUpdate();
    }
  }, 20 * 1000);

  document.addDocumentListener(listener);
  Disposer.register(this, () -> {
    document.removeDocumentListener(listener);
    marker.dispose();
    ourStatsAlarm.cancelAllRequests();
  });
}
 
Example #22
Source File: DocumentChangesCollector.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Updates current object's state on the basis of the given event assuming that there are no stored change ranges that
 * start after offset denoted by the given event.
 *
 * @param event     event for just occurred document change
 * @param oldText   our main idea is to merge all changes in order to have aggregated change against original document. So, there is
 *                  a possible case that subsequent change affects text inserted by the previous one. We don't want to reflect that
 *                  at aggregated change as it didn't appear in initial document. Hence, we have a mutable symbols buffer that holds
 *                  symbols from initial document affected by the given change
 */
private void updateChanges(DocumentEvent event, StringBuilder oldText) {
  int i = findIndex(event.getOffset());
  int endOffset = event.getOffset() + event.getNewLength();
  TextChangeImpl change = new TextChangeImpl(oldText, event.getOffset(), endOffset);
  if (i < 0) {
    myChanges.add(change);
  }
  else {
    myChanges.add(i, change);
  }
}
 
Example #23
Source File: UnifiedDiffViewer.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected void onDocumentChange(@Nonnull DocumentEvent e) {
  if (myDuringTwosideDocumentModification) return;

  markStateIsOutOfDate();
  markSuppressEditorTyping();

  scheduleRediff();
}
 
Example #24
Source File: QuickEditHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void documentChanged(DocumentEvent e) {
  UndoManager undoManager = UndoManager.getInstance(myProject);
  boolean undoOrRedo = undoManager.isUndoInProgress() || undoManager.isRedoInProgress();
  if (undoOrRedo) {
    // allow undo/redo up until 'creation stamp' back in time
    // and check it after action is completed
    if (e.getDocument() == myOrigDocument) {
      //noinspection SSBasedInspection
      SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
          if (myOrigCreationStamp > myOrigDocument.getModificationStamp()) {
            closeEditor();
          }
        }
      });
    }
  }
  else if (e.getDocument() == myNewDocument) {
    commitToOriginal(e);
    if (!isValid()) {
      ApplicationManager.getApplication().invokeLater(new Runnable() {
        @Override
        public void run() {
          closeEditor();
        }
      }, myProject.getDisposed());
    }
  }
  else if (e.getDocument() == myOrigDocument) {
    if (myCommittingToOriginal || myAltFullRange != null && myAltFullRange.isValid()) return;
    ApplicationManager.getApplication().invokeLater(new Runnable() {
      @Override
      public void run() {
        closeEditor();
      }
    }, myProject.getDisposed());
  }
}
 
Example #25
Source File: SimpleDiffViewer.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@RequiredUIAccess
protected void onBeforeDocumentChange(@Nonnull DocumentEvent e) {
  super.onBeforeDocumentChange(e);
  if (myDiffChanges.isEmpty()) return;

  List<Document> documents = ContainerUtil.map(getEditors(), Editor::getDocument);
  Side side = Side.fromValue(documents, e.getDocument());
  if (side == null) {
    LOG.warn("Unknown document changed");
    return;
  }

  LineRange lineRange = DiffUtil.getAffectedLineRange(e);
  int shift = DiffUtil.countLinesShift(e);

  List<SimpleDiffChange> invalid = new ArrayList<>();
  for (SimpleDiffChange change : myDiffChanges) {
    if (change.processChange(lineRange.start, lineRange.end, shift, side)) {
      invalid.add(change);
    }
  }

  if (!invalid.isEmpty()) {
    myDiffChanges.removeAll(invalid);
    myInvalidDiffChanges.addAll(invalid);
  }
}
 
Example #26
Source File: InplaceChangeSignature.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void documentChanged(DocumentEvent event) {
  RangeMarker marker = event.getDocument().createRangeMarker(event.getOffset(), event.getOffset());
  myDocumentManager.performWhenAllCommitted(() -> {
    if (myDetector == null) {
      return;
    }
    PsiFile file = myDocumentManager.getPsiFile(event.getDocument());
    if (file == null) {
      return;
    }
    PsiElement element = file.findElementAt(marker.getStartOffset());
    marker.dispose();
    if (element == null || myDetector.ignoreChanges(element)) return;

    if (element instanceof PsiWhiteSpace) {
      PsiElement method = myStableChange.getMethod();
      if (PsiTreeUtil.skipSiblingsForward(element, PsiWhiteSpace.class) == method) {
        return;
      }
    }

    if (!myDetector.isChangeSignatureAvailableOnElement(element, myStableChange)) {
      detach();
      return;
    }

    updateCurrentInfo();
  });
}
 
Example #27
Source File: OffsetTranslator.java    From consulo with Apache License 2.0 5 votes vote down vote up
public OffsetTranslator(Document originalDocument, PsiFile originalFile, Document copyDocument, int start, int end, String replacement) {
  myOriginalFile = originalFile;
  myCopyDocument = copyDocument;
  myCopyDocument.putUserData(RANGE_TRANSLATION, this);
  myTranslation.addFirst(new DocumentEventImpl(copyDocument, start, originalDocument.getImmutableCharSequence().subSequence(start, end), replacement, 0, false));
  Disposer.register(originalFile.getProject(), this);

  final LinkedList<DocumentEvent> sinceCommit = new LinkedList<>();
  originalDocument.addDocumentListener(new DocumentListener() {
    @Override
    public void documentChanged(@Nonnull DocumentEvent e) {
      if (isUpToDate()) {
        DocumentEventImpl inverse = new DocumentEventImpl(originalDocument, e.getOffset(), e.getNewFragment(), e.getOldFragment(), 0, false);
        sinceCommit.addLast(inverse);
      }
    }
  }, this);

  originalFile.getProject().getMessageBus().connect(this).subscribe(PsiModificationTracker.TOPIC, new PsiModificationTracker.Listener() {
    final long lastModCount = originalFile.getViewProvider().getModificationStamp();

    @Override
    public void modificationCountChanged() {
      if (isUpToDate() && lastModCount != originalFile.getViewProvider().getModificationStamp()) {
        myTranslation.addAll(sinceCommit);
        sinceCommit.clear();
      }
    }
  });

}
 
Example #28
Source File: DocumentUndoProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void handleDocumentChanged(@Nonnull UndoManagerImpl undoManager, @Nonnull Document document, @Nonnull DocumentEvent e) {
  if (undoManager.isActive() && isUndoable(undoManager, document)) {
    registerUndoableAction(undoManager, e);
  }
  else {
    registerNonUndoableAction(undoManager, document);
  }
}
 
Example #29
Source File: LookupOffsets.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void documentChanged(@Nonnull DocumentEvent e) {
  if (myStartMarkerDisposeInfo == null && !myLookupStartMarker.isValid()) {
    Throwable throwable = new Throwable();
    String eString = e.toString();
    myStartMarkerDisposeInfo = () -> eString + "\n" + ExceptionUtil.getThrowableText(throwable);
  }
}
 
Example #30
Source File: DocumentImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void changedUpdate(@Nonnull DocumentEvent event, long newModificationStamp, @Nonnull CharSequence prevText, DelayedExceptions exceptions) {
  try {
    if (LOG.isTraceEnabled()) LOG.trace(new Throwable(event.toString()));
    else if (LOG.isDebugEnabled()) LOG.debug(event.toString());

    assert event.getOldFragment().length() == event.getOldLength() : "event.getOldFragment().length() = " + event.getOldFragment().length() + "; event.getOldLength() = " + event.getOldLength();
    assert event.getNewFragment().length() == event.getNewLength() : "event.getNewFragment().length() = " + event.getNewFragment().length() + "; event.getNewLength() = " + event.getNewLength();
    assert prevText.length() + event.getNewLength() - event.getOldLength() == getTextLength() : "prevText.length() = " +
                                                                                                prevText.length() +
                                                                                                "; event.getNewLength() = " +
                                                                                                event.getNewLength() +
                                                                                                "; event.getOldLength() = " +
                                                                                                event.getOldLength() +
                                                                                                "; getTextLength() = " +
                                                                                                getTextLength();

    myLineSet = getLineSet().update(prevText, event.getOffset(), event.getOffset() + event.getOldLength(), event.getNewFragment(), event.isWholeTextReplaced());
    assert getTextLength() == myLineSet.getLength() : "getTextLength() = " + getTextLength() + "; myLineSet.getLength() = " + myLineSet.getLength();

    myFrozen = null;
    setModificationStamp(newModificationStamp);

    if (!ShutDownTracker.isShutdownHookRunning()) {
      DocumentListener[] listeners = getListeners();
      for (DocumentListener listener : listeners) {
        try {
          listener.documentChanged(event);
        }
        catch (Throwable e) {
          exceptions.register(e);
        }
      }
    }
  }
  finally {
    myEventsHandling = false;
  }
}