Java Code Examples for com.intellij.openapi.editor.event.DocumentEvent#getOldLength()

The following examples show how to use com.intellij.openapi.editor.event.DocumentEvent#getOldLength() . 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: LineStatusTrackerBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private int[] fixRanges(@Nonnull DocumentEvent e, int line1, int line2) {
  CharSequence document = myDocument.getCharsSequence();
  int offset = e.getOffset();

  if (e.getOldLength() == 0 && e.getNewLength() != 0) {
    if (StringUtil.endsWithChar(e.getNewFragment(), '\n') && isNewline(offset - 1, document)) {
      return new int[]{line1, line2 - 1};
    }
    if (StringUtil.startsWithChar(e.getNewFragment(), '\n') && isNewline(offset + e.getNewLength(), document)) {
      return new int[]{line1 + 1, line2};
    }
  }
  if (e.getOldLength() != 0 && e.getNewLength() == 0) {
    if (StringUtil.endsWithChar(e.getOldFragment(), '\n') && isNewline(offset - 1, document)) {
      return new int[]{line1, line2 - 1};
    }
    if (StringUtil.startsWithChar(e.getOldFragment(), '\n') && isNewline(offset + e.getNewLength(), document)) {
      return new int[]{line1 + 1, line2};
    }
  }

  return new int[]{line1, line2};
}
 
Example 2
Source File: FoldingModelImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
boolean collectAffectedMarkersAndShiftSubtrees(@Nullable IntervalNode<FoldRegionImpl> root, @Nonnull DocumentEvent e, @Nonnull List<? super IntervalNode<FoldRegionImpl>> affected) {
  if (inCollectCall) return super.collectAffectedMarkersAndShiftSubtrees(root, e, affected);
  inCollectCall = true;
  boolean result;
  try {
    result = super.collectAffectedMarkersAndShiftSubtrees(root, e, affected);
  }
  finally {
    inCollectCall = false;
  }
  if (e.getOldLength() > 0 /* document change can cause regions to become equal*/) {
    for (Object o : affected) {
      //noinspection unchecked
      Node<FoldRegionImpl> node = (Node<FoldRegionImpl>)o;
      FoldRegionImpl region = getRegion(node);
      // region with the largest metric value is kept when several regions become identical after document change
      // we want the largest collapsed region to survive
      region.mySizeBeforeUpdate = region.isExpanded() ? 0 : node.intervalEnd() - node.intervalStart();
    }
  }
  return result;
}
 
Example 3
Source File: RangeMarkerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
private static TextRange processIfOnePoint(@Nonnull DocumentEvent e, int intervalStart, boolean greedyRight, boolean stickyRight) {
  int offset = e.getOffset();
  int oldLength = e.getOldLength();
  int oldEnd = offset + oldLength;
  if (offset < intervalStart && intervalStart < oldEnd) {
    return null;
  }

  if (offset == intervalStart && oldLength == 0) {
    if (greedyRight) {
      return new UnfairTextRange(intervalStart, intervalStart + e.getNewLength());
    }
    else if (stickyRight) {
      return new UnfairTextRange(intervalStart + e.getNewLength(), intervalStart + e.getNewLength());
    }
  }

  if (intervalStart > oldEnd || intervalStart == oldEnd && oldLength > 0) {
    return new UnfairTextRange(intervalStart + e.getNewLength() - oldLength, intervalStart + e.getNewLength() - oldLength);
  }

  return new UnfairTextRange(intervalStart, intervalStart);
}
 
Example 4
Source File: LanguageConsoleBuilder.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void documentChanged(DocumentEvent event) {
  DocumentEx document = getDocument();
  if (document.isInBulkUpdate()) {
    return;
  }

  if (document.getTextLength() > 0) {
    addLineSeparatorPainterIfNeed();
    int startDocLine = document.getLineNumber(event.getOffset());
    int endDocLine = document.getLineNumber(event.getOffset() + event.getNewLength());
    if (event.getOldLength() > event.getNewLength() || startDocLine != endDocLine || StringUtil.indexOf(event.getOldFragment(), '\n') != -1) {
      updateGutterSize(startDocLine, endDocLine);
    }
  }
  else if (event.getOldLength() > 0) {
    documentCleared();
  }
}
 
Example 5
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 6
Source File: DocumentContentSynchronizer.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Convert IntelliJ {@link DocumentEvent} to LS according {@link TextDocumentSyncKind}.
 *
 * @param event
 *            IntelliJ {@link DocumentEvent}
 * @return true if change event is ready to be sent
 */
private boolean createChangeEvent(DocumentEvent event) {
    changeParams = new DidChangeTextDocumentParams(new VersionedTextDocumentIdentifier(), Collections.singletonList(new TextDocumentContentChangeEvent()));
    changeParams.getTextDocument().setUri(fileUri.toString());

    Document document = event.getDocument();
    TextDocumentContentChangeEvent changeEvent = null;
    TextDocumentSyncKind syncKind = getTextDocumentSyncKind();
    switch (syncKind) {
        case None:
            return false;
        case Full:
            changeParams.getContentChanges().get(0).setText(event.getDocument().getText());
            break;
        case Incremental:
            changeEvent = changeParams.getContentChanges().get(0);
            CharSequence newText = event.getNewFragment();
            int offset = event.getOffset();
            int length = event.getOldLength();
            try {
                // try to convert the Eclipse start/end offset to LS range.
                Range range = new Range(LSPIJUtils.toPosition(offset, document),
                        LSPIJUtils.toPosition(offset + length, document));
                changeEvent.setRange(range);
                changeEvent.setText(newText.toString());
                changeEvent.setRangeLength(length);
            } finally {
            }
            break;
    }
    return true;
}
 
Example 7
Source File: DocumentFragmentContent.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected void onDocumentChanged2(@Nonnull DocumentEvent event) {
  if (!myRangeMarker.isValid()) return;
  if (!myDocument1.isWritable()) return;

  CharSequence newText = event.getNewFragment();
  int originalOffset = event.getOffset() + myRangeMarker.getStartOffset();
  int originalEnd = originalOffset + event.getOldLength();
  replaceString(myDocument1, originalOffset, originalEnd, newText);
}
 
Example 8
Source File: FragmentContent.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCopyChanged(@Nonnull DocumentEvent event, @Nonnull Document original) {
  final int originalOffset = event.getOffset() + myRangeMarker.getStartOffset();
  LOG.assertTrue(originalOffset >= 0);
  if (!original.isWritable()) return;
  final String newText = subText(event.getDocument(), event.getOffset(), event.getNewLength());
  final int originalEnd = originalOffset + event.getOldLength();
  replaceString(original, originalOffset, originalEnd, newText);
}
 
Example 9
Source File: ChangedPsiRangeUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
static ProperTextRange getChangedPsiRange(@Nonnull PsiFile file, @Nonnull Document document, @Nonnull CharSequence oldDocumentText, @Nonnull CharSequence newDocumentText) {
  int psiLength = oldDocumentText.length();
  if (!file.getViewProvider().supportsIncrementalReparse(file.getLanguage())) {
    return new ProperTextRange(0, psiLength);
  }
  List<DocumentEvent> events = ((PsiDocumentManagerBase)PsiDocumentManager.getInstance(file.getProject())).getEventsSinceCommit(document);
  int prefix = Integer.MAX_VALUE;
  int suffix = Integer.MAX_VALUE;
  int lengthBeforeEvent = psiLength;
  for (DocumentEvent event : events) {
    prefix = Math.min(prefix, event.getOffset());
    suffix = Math.min(suffix, lengthBeforeEvent - event.getOffset() - event.getOldLength());
    lengthBeforeEvent = lengthBeforeEvent - event.getOldLength() + event.getNewLength();
  }
  if ((prefix == psiLength || suffix == psiLength) && newDocumentText.length() == psiLength) {
    return null;
  }
  //Important! delete+insert sequence can give some of same chars back, lets grow affixes to include them.
  int shortestLength = Math.min(psiLength, newDocumentText.length());
  while (prefix < shortestLength && oldDocumentText.charAt(prefix) == newDocumentText.charAt(prefix)) {
    prefix++;
  }
  while (suffix < shortestLength - prefix && oldDocumentText.charAt(psiLength - suffix - 1) == newDocumentText.charAt(newDocumentText.length() - suffix - 1)) {
    suffix++;
  }
  int end = Math.max(prefix, psiLength - suffix);
  if (end == prefix && newDocumentText.length() == oldDocumentText.length()) return null;
  return ProperTextRange.create(prefix, end);
}
 
Example 10
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 11
Source File: FoldRegionImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected void changedUpdateImpl(@Nonnull DocumentEvent e) {
  if (isValid()) {
    int oldStart = intervalStart();
    int oldEnd = intervalEnd();
    int changeStart = e.getOffset();
    int changeEnd = e.getOffset() + e.getOldLength();
    if (changeStart < oldEnd && changeEnd > oldStart) myDocumentRegionWasChanged = true;
  }
  super.changedUpdateImpl(e);
  if (isValid()) {
    alignToSurrogateBoundaries();
  }
}
 
Example 12
Source File: LineOrientedDocumentChangeAdapter.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeDocumentChange(DocumentEvent event) {
  Document document = event.getDocument();
  int startLine = document.getLineNumber(normalize(event.getDocument(), event.getOffset()));
  int endLine = document.getLineNumber(normalize(event.getDocument(), event.getOffset() + event.getOldLength()));
  int symbolsDifference = event.getNewLength() - event.getOldLength();
  beforeDocumentChange(startLine, endLine, symbolsDifference);
}
 
Example 13
Source File: LineOrientedDocumentChangeAdapter.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void documentChanged(DocumentEvent event) {
  Document document = event.getDocument();
  int startLine = document.getLineNumber(normalize(event.getDocument(), event.getOffset()));
  int endLine = document.getLineNumber(normalize(event.getDocument(), event.getOffset() + event.getNewLength()));
  int symbolsDifference = event.getNewLength() - event.getOldLength();
  afterDocumentChange(startLine, endLine, symbolsDifference);
}
 
Example 14
Source File: OffsetTranslator.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private static Integer translateOffset(int offset, DocumentEvent event) {
  if (event.getOffset() < offset && offset < event.getOffset() + event.getNewLength()) {
    if (event.getOldLength() == 0) {
      return event.getOffset();
    }

    return null;
  }

  return offset <= event.getOffset() ? offset : offset - event.getNewLength() + event.getOldLength();
}
 
Example 15
Source File: FrozenDocument.java    From consulo with Apache License 2.0 5 votes vote down vote up
public FrozenDocument applyEvent(DocumentEvent event, int newStamp) {
  final int offset = event.getOffset();
  final int oldEnd = offset + event.getOldLength();
  ImmutableCharSequence newText = myText.delete(offset, oldEnd).insert(offset, event.getNewFragment());
  LineSet newLineSet = getLineSet().update(myText, offset, oldEnd, event.getNewFragment(), event.isWholeTextReplaced());
  return new FrozenDocument(newText, newLineSet, newStamp, null);
}
 
Example 16
Source File: TextInputListener.java    From tmc-intellij with MIT License 4 votes vote down vote up
private boolean isRemoveEvent(DocumentEvent documentEvent) {
    return (documentEvent.getOldLength() > 0 && documentEvent.getNewLength() == 0);
}
 
Example 17
Source File: EditorComponentImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
/** Redispatch an IDE {@link DocumentEvent} to a Swing {@link javax.swing.event.DocumentListener} */
private void fireJTextComponentDocumentChange(final DocumentEvent event) {
  //noinspection deprecation
  List<javax.swing.event.DocumentListener> listeners = ((EditorAccessibilityDocument)getDocument()).getListeners();
  if (listeners == null) {
    return;
  }

  javax.swing.event.DocumentEvent swingEvent = new javax.swing.event.DocumentEvent() {
    @Override
    public int getOffset() {
      return event.getOffset();
    }

    @Override
    public int getLength() {
      return event.getNewLength();
    }

    @Override
    public javax.swing.text.Document getDocument() {
      //noinspection deprecation
      return EditorComponentImpl.this.getDocument();
    }

    @Override
    public EventType getType() {
      return event.getOldLength() == 0 ? EventType.INSERT : event.getNewLength() == 0 ? EventType.REMOVE : EventType.CHANGE;
    }

    @Nullable
    @Override
    public ElementChange getChange(Element element) {
      return null;
    }
  };
  for (javax.swing.event.DocumentListener listener : listeners) {
    javax.swing.event.DocumentEvent.EventType type = swingEvent.getType();
    if (type == javax.swing.event.DocumentEvent.EventType.INSERT) {
      listener.insertUpdate(swingEvent);
    } else if (type == javax.swing.event.DocumentEvent.EventType.REMOVE) {
      listener.removeUpdate(swingEvent);
    } else if (type == javax.swing.event.DocumentEvent.EventType.CHANGE) {
      listener.changedUpdate(swingEvent);
    }
  }
}
 
Example 18
Source File: DesktopCaretImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
protected void changedUpdateImpl(@Nonnull DocumentEvent e) {
  int oldOffset = intervalStart();
  super.changedUpdateImpl(e);
  if (isValid()) {
    // Under certain conditions, when text is inserted at caret position, we position caret at the end of inserted text.
    // Ideally, client code should be responsible for positioning caret after document modification, but in case of
    // postponed formatting (after PSI modifications), this is hard to implement, so a heuristic below is used.
    if (e.getOldLength() == 0 &&
        oldOffset == e.getOffset() &&
        !Boolean.TRUE.equals(myEditor.getUserData(DesktopEditorImpl.DISABLE_CARET_SHIFT_ON_WHITESPACE_INSERTION)) &&
        needToShiftWhiteSpaces(e)) {
      int afterInserted = e.getOffset() + e.getNewLength();
      setIntervalStart(afterInserted);
      setIntervalEnd(afterInserted);
    }
    int offset = intervalStart();
    if (DocumentUtil.isInsideSurrogatePair(getDocument(), offset)) {
      setIntervalStart(offset - 1);
      setIntervalEnd(offset - 1);
    }
  }
  else {
    setValid(true);
    int newOffset = Math.min(intervalStart(), e.getOffset() + e.getNewLength());
    if (!e.getDocument().isInBulkUpdate() && e.isWholeTextReplaced()) {
      try {
        final int line = ((DocumentEventImpl)e).translateLineViaDiff(myLogicalCaret.line);
        newOffset = myEditor.logicalPositionToOffset(new LogicalPosition(line, myLogicalCaret.column));
      }
      catch (FilesTooBigForDiffException ex) {
        LOG.info(ex);
      }
    }
    newOffset = DocumentUtil.alignToCodePointBoundary(getDocument(), newOffset);
    setIntervalStart(newOffset);
    setIntervalEnd(newOffset);
  }
  myLogicalColumnAdjustment = 0;
  myVisualColumnAdjustment = 0;
  if (oldOffset >= e.getOffset() && oldOffset <= e.getOffset() + e.getOldLength() && e.getNewLength() == 0 && e.getOldLength() > 0) {
    int inlaysToTheLeft = myEditor.getInlayModel().getInlineElementsInRange(e.getOffset(), e.getOffset()).size();
    boolean hasInlaysToTheRight = myEditor.getInlayModel().hasInlineElementAt(e.getOffset() + e.getOldLength());
    if (inlaysToTheLeft > 0 || hasInlaysToTheRight) {
      myLeansTowardsLargerOffsets = !hasInlaysToTheRight;
      myVisualColumnAdjustment = hasInlaysToTheRight ? inlaysToTheLeft : 0;
    }
    else if (oldOffset == e.getOffset()) {
      myLeansTowardsLargerOffsets = false;
    }
  }
}
 
Example 19
Source File: EmptyEditorHighlighter.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public void documentChanged(DocumentEvent e) {
  myTextLength += e.getNewLength() - e.getOldLength();
}
 
Example 20
Source File: IncrementalCacheUpdateEvent.java    From consulo with Apache License 2.0 2 votes vote down vote up
/**
 * Creates new {@code IncrementalCacheUpdateEvent} object on the basis on the given event object that describes
 * document change that caused cache update.
 * <p/>
 * This constructor is assumed to be used <b>before</b> the document change.
 *
 * @param event object that describes document change that caused cache update
 */
IncrementalCacheUpdateEvent(@Nonnull DocumentEvent event, @Nonnull DesktopEditorImpl editor) {
  this(event.getOffset(), event.getOffset() + event.getOldLength(), event.getOffset() + event.getNewLength(), editor);
}