Java Code Examples for com.intellij.openapi.editor.RangeMarker#isValid()

The following examples show how to use com.intellij.openapi.editor.RangeMarker#isValid() . 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: HaxeDocumentModel.java    From intellij-haxe with Apache License 2.0 6 votes vote down vote up
/**
 * Replace the text within the given range and reformat it according to the user's
 * code style/formatting rules.
 *
 * NOTE: The PSI may be entirely invalidated and re-created by this call.
 *
 * @param range Range of text or PsiElements to replace.
 * @param text Replacement text (may be null).
 */
public void replaceAndFormat(@NotNull final TextRange range, @Nullable String text) {
  if (null == text) {
    text = "";
  }

  // Mark the beginning and end so that we have the proper range after adding text.
  // Greedy means that the text immediately added at the beginning/end of the marker are included.
  RangeMarker marker = document.createRangeMarker(range);
  marker.setGreedyToLeft(true);
  marker.setGreedyToRight(true);

  try {

    document.replaceString(range.getStartOffset(), range.getEndOffset(), text);

    //PsiDocumentManager.getInstance(file.getProject()).commitDocument(document); // force update PSI.

    if (marker.isValid()) { // If the range wasn't reduced to zero.
      CodeStyleManager.getInstance(file.getProject()).reformatText(file, marker.getStartOffset(), marker.getEndOffset());
    }
  }
  finally {
    marker.dispose();
  }
}
 
Example 2
Source File: FileStatusMap.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * @return null for processed file, whole file for untouched or entirely dirty file, range(usually code block) for dirty region (optimization)
 */
@Nullable
public TextRange getFileDirtyScope(@Nonnull Document document, int passId) {
  synchronized (myDocumentToStatusMap) {
    PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(document);
    if (!ProblemHighlightFilter.shouldHighlightFile(file)) return null;
    FileStatus status = myDocumentToStatusMap.get(document);
    if (status == null) {
      return file == null ? null : file.getTextRange();
    }
    if (status.defensivelyMarked) {
      status.markWholeFileDirty(myProject);
      status.defensivelyMarked = false;
    }
    if (!status.dirtyScopes.containsKey(passId)) throw new IllegalStateException("Unknown pass " + passId);
    RangeMarker marker = status.dirtyScopes.get(passId);
    return marker == null ? null : marker.isValid() ? TextRange.create(marker) : new TextRange(0, document.getTextLength());
  }
}
 
Example 3
Source File: OffsetMap.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * @param key key
 * @return offset An offset registered earlier with this key.
 * -1 if offset wasn't registered or became invalidated due to document changes
 */
public int getOffset(OffsetKey key) {
  synchronized (myMap) {
    final RangeMarker marker = myMap.get(key);
    if (marker == null) throw new IllegalArgumentException("Offset " + key + " is not registered");
    if (!marker.isValid()) {
      removeOffset(key);
      throw new IllegalStateException("Offset " + key + " is invalid: " + marker);
    }

    final int endOffset = marker.getEndOffset();
    if (marker.getStartOffset() != endOffset) {
      saveOffset(key, endOffset, false);
    }
    return endOffset;
  }
}
 
Example 4
Source File: EventLog.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void insertNewLineSubstitutors(Document document, AtomicBoolean showMore, List<RangeMarker> lineSeparators) {
  for (RangeMarker marker : lineSeparators) {
    if (!marker.isValid()) {
      showMore.set(true);
      continue;
    }

    int offset = marker.getStartOffset();
    if (offset == 0 || offset == document.getTextLength()) {
      continue;
    }
    boolean spaceBefore = offset > 0 && Character.isWhitespace(document.getCharsSequence().charAt(offset - 1));
    if (offset < document.getTextLength()) {
      boolean spaceAfter = Character.isWhitespace(document.getCharsSequence().charAt(offset));
      int next = CharArrayUtil.shiftForward(document.getCharsSequence(), offset, " \t");
      if (next < document.getTextLength() && !Character.isLowerCase(document.getCharsSequence().charAt(next))) {
        document.insertString(offset, (spaceBefore ? "" : " ") + "//" + (spaceAfter ? "" : " "));
        continue;
      }
      if (spaceAfter) {
        continue;
      }
    }
    if (spaceBefore) {
      continue;
    }

    document.insertString(offset, " ");
  }
}
 
Example 5
Source File: SearchResults.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void updateExcluded() {
  Set<RangeMarker> invalid = new HashSet<>();
  for (RangeMarker marker : myExcluded) {
    if (!marker.isValid()) {
      invalid.add(marker);
      marker.dispose();
    }
  }
  myExcluded.removeAll(invalid);
}
 
Example 6
Source File: PostprocessReformattingAspect.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void dispose() {
  for (Pair<Integer, RangeMarker> pair : myRangesToReindent) {
    RangeMarker marker = pair.second;
    if (marker.isValid()) {
      marker.dispose();
    }
  }
}
 
Example 7
Source File: DocumentFoldingInfo.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean equals(Object o) {
  if (this == o) {
    return true;
  }
  if (o == null || getClass() != o.getClass()) {
    return false;
  }

  DocumentFoldingInfo info = (DocumentFoldingInfo)o;

  if (myFile != null ? !myFile.equals(info.myFile) : info.myFile != null) {
    return false;
  }
  if (!myProject.equals(info.myProject) || !myInfos.equals(info.myInfos)) {
    return false;
  }

  if (myRangeMarkers.size() != info.myRangeMarkers.size()) return false;
  for (int i = 0; i < myRangeMarkers.size(); i++) {
    RangeMarker marker = myRangeMarkers.get(i);
    RangeMarker other = info.myRangeMarkers.get(i);
    if (marker == other || !marker.isValid() || !other.isValid()) {
      continue;
    }
    if (!TextRange.areSegmentsEqual(marker, other)) return false;

    FoldingInfo fi = marker.getUserData(FOLDING_INFO_KEY);
    FoldingInfo ofi = other.getUserData(FOLDING_INFO_KEY);
    if (!Comparing.equal(fi, ofi)) return false;
  }
  return true;
}
 
Example 8
Source File: TodoPanel.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void updatePreviewPanel() {
  if (myProject == null || myProject.isDisposed()) return;
  List<UsageInfo> infos = new ArrayList<>();
  final TreePath path = myTree.getSelectionPath();
  if (path != null) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
    Object userObject = node.getUserObject();
    if (userObject instanceof NodeDescriptor) {
      Object element = ((NodeDescriptor)userObject).getElement();
      TodoItemNode pointer = myTodoTreeBuilder.getFirstPointerForElement(element);
      if (pointer != null) {
        final SmartTodoItemPointer value = pointer.getValue();
        final Document document = value.getDocument();
        final PsiFile psiFile = PsiDocumentManager.getInstance(myProject).getPsiFile(document);
        final RangeMarker rangeMarker = value.getRangeMarker();
        if (psiFile != null) {
          infos.add(new UsageInfo(psiFile, rangeMarker.getStartOffset(), rangeMarker.getEndOffset()));
          for (RangeMarker additionalMarker : value.getAdditionalRangeMarkers()) {
            if (additionalMarker.isValid()) {
              infos.add(new UsageInfo(psiFile, additionalMarker.getStartOffset(), additionalMarker.getEndOffset()));
            }
          }
        }
      }
    }
  }
  myUsagePreviewPanel.updateLayout(infos.isEmpty() ? null : infos);
}
 
Example 9
Source File: Bookmark.java    From consulo with Apache License 2.0 5 votes vote down vote up
public int getLine() {
  RangeMarker marker = myTarget.getRangeMarker();
  if (marker != null && marker.isValid()) {
    Document document = marker.getDocument();
    return document.getLineNumber(marker.getStartOffset());
  }
  return myTarget.getLine();
}
 
Example 10
Source File: Bookmark.java    From consulo with Apache License 2.0 5 votes vote down vote up
public boolean isValid() {
  if (!getFile().isValid()) {
    return false;
  }

  // There is a possible case that target document line that is referenced by the current bookmark is removed. We assume
  // that corresponding range marker becomes invalid then.
  RangeMarker rangeMarker = myTarget.getRangeMarker();
  return rangeMarker == null || rangeMarker.isValid();
}
 
Example 11
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 12
Source File: EventLog.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static String getStatusText(DocumentImpl logDoc, AtomicBoolean showMore, List<RangeMarker> lineSeparators, String indent, boolean hasHtml) {
  DocumentImpl statusDoc = new DocumentImpl(logDoc.getImmutableCharSequence(), true);
  List<RangeMarker> statusSeparators = new ArrayList<RangeMarker>();
  for (RangeMarker separator : lineSeparators) {
    if (separator.isValid()) {
      statusSeparators.add(statusDoc.createRangeMarker(separator.getStartOffset(), separator.getEndOffset()));
    }
  }
  removeJavaNewLines(statusDoc, statusSeparators, indent, hasHtml);
  insertNewLineSubstitutors(statusDoc, showMore, statusSeparators);

  return statusDoc.getText();
}
 
Example 13
Source File: EventLog.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void indentNewLines(DocumentImpl logDoc, List<RangeMarker> lineSeparators, RangeMarker afterTitle, boolean hasHtml, String indent) {
  if (!hasHtml) {
    int i = -1;
    while (true) {
      i = StringUtil.indexOf(logDoc.getText(), '\n', i + 1);
      if (i < 0) {
        break;
      }
      lineSeparators.add(logDoc.createRangeMarker(i, i + 1));
    }
  }
  if (!lineSeparators.isEmpty() && afterTitle != null && afterTitle.isValid()) {
    lineSeparators.add(afterTitle);
  }
  int nextLineStart = -1;
  for (RangeMarker separator : lineSeparators) {
    if (separator.isValid()) {
      int start = separator.getStartOffset();
      if (start == nextLineStart) {
        continue;
      }

      logDoc.replaceString(start, separator.getEndOffset(), "\n" + indent);
      nextLineStart = start + 1 + indent.length();
      while (nextLineStart < logDoc.getTextLength() && Character.isWhitespace(logDoc.getCharsSequence().charAt(nextLineStart))) {
        logDoc.deleteString(nextLineStart, nextLineStart + 1);
      }
    }
  }
}
 
Example 14
Source File: ChunkExtractor.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static int getStartOffset(final List<RangeMarker> rangeMarkers) {
  LOG.assertTrue(!rangeMarkers.isEmpty());
  int minStart = Integer.MAX_VALUE;
  for (RangeMarker rangeMarker : rangeMarkers) {
    if (!rangeMarker.isValid()) continue;
    final int startOffset = rangeMarker.getStartOffset();
    if (startOffset < minStart) minStart = startOffset;
  }
  return minStart == Integer.MAX_VALUE ? -1 : minStart;
}
 
Example 15
Source File: ConsoleLog.java    From aem-ide-tooling-4-intellij with Apache License 2.0 5 votes vote down vote up
private static void insertNewLineSubstitutors(Document document, AtomicBoolean showMore, List<RangeMarker> lineSeparators) {
    for(RangeMarker marker : lineSeparators) {
        if(!marker.isValid()) {
            showMore.set(true);
            continue;
        }

        int offset = marker.getStartOffset();
        if(offset == 0 || offset == document.getTextLength()) {
            continue;
        }
        boolean spaceBefore = offset > 0 && Character.isWhitespace(document.getCharsSequence().charAt(offset - 1));
        if(offset < document.getTextLength()) {
            boolean spaceAfter = Character.isWhitespace(document.getCharsSequence().charAt(offset));
            int next = CharArrayUtil.shiftForward(document.getCharsSequence(), offset, " \t");
            if(next < document.getTextLength() && !Character.isLowerCase(document.getCharsSequence().charAt(next))) {
                document.insertString(offset, (spaceBefore ? "" : " ") + "//" + (spaceAfter ? "" : " "));
                continue;
            }
            if(spaceAfter) {
                continue;
            }
        }
        if(spaceBefore) {
            continue;
        }

        document.insertString(offset, " ");
    }
}
 
Example 16
Source File: ConsoleLog.java    From aem-ide-tooling-4-intellij with Apache License 2.0 5 votes vote down vote up
private static String getStatusText(DocumentImpl logDoc, AtomicBoolean showMore, List<RangeMarker> lineSeparators, boolean hasHtml) {
    DocumentImpl statusDoc = new DocumentImpl(logDoc.getImmutableCharSequence(), true);
    List<RangeMarker> statusSeparators = new ArrayList<RangeMarker>();
    for(RangeMarker separator : lineSeparators) {
        if(separator.isValid()) {
            statusSeparators.add(statusDoc.createRangeMarker(separator.getStartOffset(), separator.getEndOffset()));
        }
    }
    removeJavaNewLines(statusDoc, statusSeparators, hasHtml);
    insertNewLineSubstitutors(statusDoc, showMore, statusSeparators);

    return statusDoc.getText();
}
 
Example 17
Source File: ConsoleLog.java    From aem-ide-tooling-4-intellij with Apache License 2.0 5 votes vote down vote up
private static void indentNewLines(DocumentImpl logDoc, List<RangeMarker> lineSeparators, RangeMarker afterTitle, boolean hasHtml, String indent) {
    if(!hasHtml) {
        int i = -1;
        while(true) {
            i = StringUtil.indexOf(logDoc.getText(), '\n', i + 1);
            if(i < 0) {
                break;
            }
            lineSeparators.add(logDoc.createRangeMarker(i, i + 1));
        }
    }
    if(!lineSeparators.isEmpty() && afterTitle != null && afterTitle.isValid()) {
        lineSeparators.add(afterTitle);
    }
    int nextLineStart = -1;
    for(RangeMarker separator : lineSeparators) {
        if(separator.isValid()) {
            int start = separator.getStartOffset();
            if(start == nextLineStart) {
                continue;
            }

            logDoc.replaceString(start, separator.getEndOffset(), "\n" + indent);
            nextLineStart = start + 1 + indent.length();
            while(nextLineStart < logDoc.getTextLength() && Character.isWhitespace(logDoc.getCharsSequence().charAt(nextLineStart))) {
                logDoc.deleteString(nextLineStart, nextLineStart + 1);
            }
        }
    }
}
 
Example 18
Source File: ConsoleLog.java    From aem-ide-tooling-4-intellij with Apache License 2.0 4 votes vote down vote up
public static LogEntry formatForLog(@NotNull final Notification notification, String indent) {
    DocumentImpl logDoc = new DocumentImpl("", true);
    AtomicBoolean showMore = new AtomicBoolean(false);
    Map<RangeMarker, HyperlinkInfo> links = new LinkedHashMap<RangeMarker, HyperlinkInfo>();
    List<RangeMarker> lineSeparators = new ArrayList<RangeMarker>();

    String title = truncateLongString(showMore, notification.getTitle());
    String content = truncateLongString(showMore, notification.getContent());

    RangeMarker afterTitle = null;
    boolean hasHtml = parseHtmlContent(title, notification, logDoc, showMore, links, lineSeparators);
    if(StringUtil.isNotEmpty(title)) {
        if(StringUtil.isNotEmpty(content)) {
            appendText(logDoc, ": ");
            afterTitle = logDoc.createRangeMarker(logDoc.getTextLength() - 2, logDoc.getTextLength());
        }
    }
    hasHtml |= parseHtmlContent(content, notification, logDoc, showMore, links, lineSeparators);

    String status = getStatusText(logDoc, showMore, lineSeparators, hasHtml);

    indentNewLines(logDoc, lineSeparators, afterTitle, hasHtml, indent);

    ArrayList<Pair<TextRange, HyperlinkInfo>> list = new ArrayList<Pair<TextRange, HyperlinkInfo>>();
    for(RangeMarker marker : links.keySet()) {
        if(!marker.isValid()) {
            showMore.set(true);
            continue;
        }
        list.add(Pair.create(new TextRange(marker.getStartOffset(), marker.getEndOffset()), links.get(marker)));
    }

    if(showMore.get()) {
        String sb = "show balloon";
        if(!logDoc.getText().endsWith(" ")) {
            appendText(logDoc, " ");
        }
        appendText(logDoc, "(" + sb + ")");
        list.add(new Pair<TextRange, HyperlinkInfo>(TextRange.from(logDoc.getTextLength() - 1 - sb.length(), sb.length()),
            new ShowBalloon(notification)));
    }

    return new LogEntry(logDoc.getText(), status, list);
}
 
Example 19
Source File: OffsetMap.java    From consulo with Apache License 2.0 4 votes vote down vote up
public boolean containsOffset(OffsetKey key) {
  final RangeMarker marker = myMap.get(key);
  return marker != null && marker.isValid();
}
 
Example 20
Source File: LazyRangeMarkerFactoryImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isValid() {
  RangeMarker delegate = getOrCreateDelegate();
  return delegate != null && !isDisposed() && delegate.isValid();
}