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

The following examples show how to use com.intellij.openapi.editor.RangeMarker#getStartOffset() . 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: TemplateSegments.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * IDEADEV-13618
 *
 * prevent two different segments to grow simultaneously if they both starts at the same offset.
 */
public void lockSegmentAtTheSameOffsetIfAny(final int number) {
  if (number == -1) {
    return;
  }

  final RangeMarker current = mySegments.get(number);
  int offset = current.getStartOffset();

  for (int i = 0; i < mySegments.size(); i++) {
    if (i != number) {
      final RangeMarker segment = mySegments.get(i);
      final int startOffset2 = segment.getStartOffset();
      if (offset == startOffset2) {
        segment.setGreedyToLeft(false);
      }
    }
  }
}
 
Example 2
Source File: SmartTodoItemPointer.java    From consulo with Apache License 2.0 6 votes vote down vote up
public boolean equals(Object obj) {
  if (!(obj instanceof SmartTodoItemPointer)) {
    return false;
  }
  SmartTodoItemPointer pointer = (SmartTodoItemPointer)obj;
  if (!(myTodoItem.getFile().equals(pointer.myTodoItem.getFile()) &&
        myRangeMarker.getStartOffset() == pointer.myRangeMarker.getStartOffset() &&
        myRangeMarker.getEndOffset() == pointer.myRangeMarker.getEndOffset() &&
        myTodoItem.getPattern().equals(pointer.myTodoItem.getPattern()) &&
        myAdditionalRangeMarkers.size() == pointer.myAdditionalRangeMarkers.size())) {
    return false;
  }
  for (int i = 0; i < myAdditionalRangeMarkers.size(); i++) {
    RangeMarker m1 = myAdditionalRangeMarkers.get(i);
    RangeMarker m2 = pointer.myAdditionalRangeMarkers.get(i);
    if (m1.getStartOffset() != m2.getStartOffset() || m1.getEndOffset() != m2.getEndOffset()) {
      return false;
    }
  }
  return true;
}
 
Example 3
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 4
Source File: Change.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * Applies the text from the original marker to the target marker.
 * @return the resulting TextRange from the target document, or null if the document if not writable.
 */
@Nullable
private static TextRange modifyDocument(@Nonnull Project project, @Nonnull RangeMarker original, @Nonnull RangeMarker target) {
  Document document = target.getDocument();
  if (!ReadonlyStatusHandler.ensureDocumentWritable(project, document)) { return null; }
  if (DocumentUtil.isEmpty(original)) {
    int offset = target.getStartOffset();
    document.deleteString(offset, target.getEndOffset());
  }
  String text = DocumentUtil.getText(original);
  int startOffset = target.getStartOffset();
  if (DocumentUtil.isEmpty(target)) {
    document.insertString(startOffset, text);
  } else {
    document.replaceString(startOffset, target.getEndOffset(), text);
  }
  return new TextRange(startOffset, startOffset + text.length());
}
 
Example 5
Source File: DaemonCodeAnalyzerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static boolean isOffsetInsideHighlightInfo(int offset, @Nonnull HighlightInfo info, boolean includeFixRange) {
  RangeHighlighterEx highlighter = info.getHighlighter();
  if (highlighter == null || !highlighter.isValid()) return false;
  int startOffset = highlighter.getStartOffset();
  int endOffset = highlighter.getEndOffset();
  if (startOffset <= offset && offset <= endOffset) {
    return true;
  }
  if (!includeFixRange) return false;
  RangeMarker fixMarker = info.fixMarker;
  if (fixMarker != null) {  // null means its range is the same as highlighter
    if (!fixMarker.isValid()) return false;
    startOffset = fixMarker.getStartOffset();
    endOffset = fixMarker.getEndOffset();
    return startOffset <= offset && offset <= endOffset;
  }
  return false;
}
 
Example 6
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 7
Source File: LSPIJUtils.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
public static void applyEdit(Editor editor, TextEdit textEdit, Document document) {
    RangeMarker marker = document.createRangeMarker(LSPIJUtils.toOffset(textEdit.getRange().getStart(), document), LSPIJUtils.toOffset(textEdit.getRange().getEnd(), document));
    int startOffset = marker.getStartOffset();
    int endOffset = marker.getEndOffset();
    String text = textEdit.getNewText();
    if (text != null) {
        text = text.replaceAll("\r", "");
    }
    if (text == null || "".equals(text)) {
        document.deleteString(startOffset, endOffset);
    } else if (endOffset - startOffset <= 0) {
        document.insertString(startOffset, text);
    } else {
        document.replaceString(startOffset, endOffset, text);
    }
    if (text != null && !"".equals(text)) {
        editor.getCaretModel().moveCaretRelatively(text.length(), 0, false, false, true);
    }
    marker.dispose();
}
 
Example 8
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 9
Source File: PostprocessReformattingAspect.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public int compareTo(@Nonnull PostprocessFormattingTask o) {
  RangeMarker o1 = myRange;
  RangeMarker o2 = o.myRange;
  if (o1.equals(o2)) return 0;
  final int diff = o2.getEndOffset() - o1.getEndOffset();
  if (diff == 0) {
    if (o1.getStartOffset() == o2.getStartOffset()) return 0;
    if (o1.getStartOffset() == o1.getEndOffset()) return -1; // empty ranges first
    if (o2.getStartOffset() == o2.getEndOffset()) return 1; // empty ranges first
    return o1.getStartOffset() - o2.getStartOffset();
  }
  return diff;
}
 
Example 10
Source File: TemplateSegments.java    From consulo with Apache License 2.0 5 votes vote down vote up
public int getSegmentWithTheSameStart(int segmentNumber, int start) {
  for (int i = segmentNumber + 1; i < mySegments.size(); i++) {
    final RangeMarker segment = mySegments.get(i);
    final int startOffset2 = segment.getStartOffset();
    if (start == startOffset2) {
      return i;
    }
  }

  return -1;
}
 
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 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 13
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 14
Source File: ExpectedHighlightingData.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void refreshLineMarkers() {
  for (Map.Entry<RangeMarker, LineMarkerInfo> entry : lineMarkerInfos.entrySet()) {
    RangeMarker rangeMarker = entry.getKey();
    int startOffset = rangeMarker.getStartOffset();
    int endOffset = rangeMarker.getEndOffset();
    final LineMarkerInfo value = entry.getValue();
    LineMarkerInfo markerInfo = new LineMarkerInfo<PsiElement>(value.getElement(), new TextRange(startOffset,endOffset), null, value.updatePass, new Function<PsiElement,String>() {
      @Override
      public String fun(PsiElement psiElement) {
        return value.getLineMarkerTooltip();
      }
    }, null, GutterIconRenderer.Alignment.RIGHT);
    entry.setValue(markerInfo);
  }
}
 
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 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 17
Source File: DocumentUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static int getLength(RangeMarker rangeMarker) {
  return rangeMarker.getEndOffset() - rangeMarker.getStartOffset();
}
 
Example 18
Source File: ShowIntentionsPass.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static void addAvailableFixesForGroups(@Nonnull HighlightInfo info,
                                               @Nonnull Editor editor,
                                               @Nonnull PsiFile file,
                                               @Nonnull List<? super HighlightInfo.IntentionActionDescriptor> outList,
                                               int group,
                                               int offset) {
  if (info.quickFixActionMarkers == null) return;
  if (group != -1 && group != info.getGroup()) return;
  boolean fixRangeIsNotEmpty = !info.getFixTextRange().isEmpty();
  Editor injectedEditor = null;
  PsiFile injectedFile = null;
  for (Pair<HighlightInfo.IntentionActionDescriptor, RangeMarker> pair : info.quickFixActionMarkers) {
    HighlightInfo.IntentionActionDescriptor actionInGroup = pair.first;
    RangeMarker range = pair.second;
    if (!range.isValid() || fixRangeIsNotEmpty && isEmpty(range)) continue;

    if (DumbService.isDumb(file.getProject()) && !DumbService.isDumbAware(actionInGroup.getAction())) {
      continue;
    }

    int start = range.getStartOffset();
    int end = range.getEndOffset();
    final Project project = file.getProject();
    if (start > offset || offset > end) {
      continue;
    }
    Editor editorToUse;
    PsiFile fileToUse;
    if (info.isFromInjection()) {
      if (injectedEditor == null) {
        injectedFile = InjectedLanguageUtil.findInjectedPsiNoCommit(file, offset);
        injectedEditor = InjectedLanguageUtil.getInjectedEditorForInjectedFile(editor, injectedFile);
      }
      editorToUse = injectedFile == null ? editor : injectedEditor;
      fileToUse = injectedFile == null ? file : injectedFile;
    }
    else {
      editorToUse = editor;
      fileToUse = file;
    }
    if (actionInGroup.getAction().isAvailable(project, editorToUse, fileToUse)) {
      outList.add(actionInGroup);
    }
  }
}
 
Example 19
Source File: DocumentUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static boolean isEmpty(@Nonnull RangeMarker rangeMarker) {
  return rangeMarker.getStartOffset() == rangeMarker.getEndOffset();
}
 
Example 20
Source File: HaxeReferenceCopyPasteProcessor.java    From intellij-haxe with Apache License 2.0 4 votes vote down vote up
@Override
public void processTransferableData(Project project, Editor editor, RangeMarker marker, int caretOffset, Ref<Boolean> indented, List<HaxeTextBlockTransferableData> values) {
  PsiDocumentManager.getInstance(project).commitAllDocuments();
  final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
  if (file == null) {
    return;
  }
  int[] startOffsets = new int[]{marker.getStartOffset()};
  int[] endOffsets = new int[]{marker.getEndOffset()};

  List<String> haxeClassList = new ArrayList<String>();

  String qualifiedName;
  for (int j = 0; j < startOffsets.length; j++) {
    final int startOffset = startOffsets[j];
    for (final PsiElement element : CollectHighlightsUtil.getElementsInRange(file, startOffset, endOffsets[j])) {
      if (element instanceof HaxeReferenceExpression) {
        HaxeReferenceExpression referenceExpression = (HaxeReferenceExpression)element;

        if (referenceExpression.resolve() == null) {
          final GlobalSearchScope scope = HaxeResolveUtil.getScopeForElement(referenceExpression);
          final List<HaxeComponent> components =
            HaxeComponentIndex.getItemsByName(referenceExpression.getText(), project, scope);
          if (!components.isEmpty() && components.size() == 1) {
            qualifiedName = ((HaxeClass)components.get(0)).getQualifiedName();
            if (!haxeClassList.contains(qualifiedName)) {
              haxeClassList.add(qualifiedName);
            }
          }
        }
      }
    }
  }

  if (haxeClassList.isEmpty()) {
    return;
  }

  HaxeRestoreReferencesDialog dialog = new HaxeRestoreReferencesDialog(project, ArrayUtil.toStringArray(haxeClassList));
  dialog.show();
  String[] selectedObjects = dialog.getSelectedElements();

  for (final String object : selectedObjects) {
    new WriteCommandAction(project, file) {
      @Override
      protected void run(@NotNull Result result) throws Throwable {
        HaxeAddImportHelper.addImport(object, file);
      }
    }.execute();
  }
}