Java Code Examples for com.intellij.openapi.util.TextRange#getStartOffset()

The following examples show how to use com.intellij.openapi.util.TextRange#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: RecentLocationsRenderer.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void selectSearchResultsInEditor(@Nonnull Editor editor, @Nonnull Iterator<? extends TextRange> resultIterator) {
  if (!editor.getCaretModel().supportsMultipleCarets()) {
    return;
  }
  ArrayList<CaretState> caretStates = new ArrayList<>();
  while (resultIterator.hasNext()) {
    TextRange findResult = resultIterator.next();

    int caretOffset = findResult.getEndOffset();

    int selectionStartOffset = findResult.getStartOffset();
    int selectionEndOffset = findResult.getEndOffset();
    EditorActionUtil.makePositionVisible(editor, caretOffset);
    EditorActionUtil.makePositionVisible(editor, selectionStartOffset);
    EditorActionUtil.makePositionVisible(editor, selectionEndOffset);
    caretStates.add(new CaretState(editor.offsetToLogicalPosition(caretOffset), editor.offsetToLogicalPosition(selectionStartOffset), editor.offsetToLogicalPosition(selectionEndOffset)));
  }
  if (caretStates.isEmpty()) {
    return;
  }
  editor.getCaretModel().setCaretsAndSelections(caretStates);
}
 
Example 2
Source File: PsiMultiReference.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public int compare(final PsiReference ref1, final PsiReference ref2) {
  if (ref1.isSoft() && !ref2.isSoft()) return 1;
  if (!ref1.isSoft() && ref2.isSoft()) return -1;

  boolean resolves1 = resolves(ref1);
  boolean resolves2 = resolves(ref2);
  if (resolves1 && !resolves2) return -1;
  if (!resolves1 && resolves2) return 1;

  final TextRange range1 = ref1.getRangeInElement();
  final TextRange range2 = ref2.getRangeInElement();

  if(TextRange.areSegmentsEqual(range1, range2)) return 0;
  if(range1.getStartOffset() >= range2.getStartOffset() && range1.getEndOffset() <= range2.getEndOffset()) return -1;
  if(range2.getStartOffset() >= range1.getStartOffset() && range2.getEndOffset() <= range1.getEndOffset()) return 1;

  return 0;
}
 
Example 3
Source File: ThreesideDiffChangeBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
protected void createInnerHighlighter(@Nonnull ThreeSide side) {
  if (isResolved(side)) return;
  MergeInnerDifferences innerFragments = getInnerFragments();
  if (innerFragments == null) return;

  List<TextRange> ranges = innerFragments.get(side);
  if (ranges == null) return;

  Editor editor = getEditor(side);
  int start = DiffUtil.getLinesRange(editor.getDocument(), getStartLine(side), getEndLine(side)).getStartOffset();
  for (TextRange fragment : ranges) {
    int innerStart = start + fragment.getStartOffset();
    int innerEnd = start + fragment.getEndOffset();
    myInnerHighlighters.addAll(DiffDrawUtil.createInlineHighlighter(editor, innerStart, innerEnd, getDiffType()));
  }
}
 
Example 4
Source File: Listener.java    From floobits-intellij with Apache License 2.0 6 votes vote down vote up
@Override
public void selectionChanged(final SelectionEvent event) {
    Document document = event.getEditor().getDocument();
    FactoryImpl iFactory = (FactoryImpl) context.iFactory;
    String path = iFactory.getPathForDoc(document);
    if (path == null) {
        return;
    }

    TextRange[] textRanges = event.getNewRanges();
    ranges = new ArrayList<ArrayList<Integer>>();
    for(TextRange r : textRanges) {
        int start = r.getStartOffset();
        int end = r.getEndOffset();
        if (start == end) {
            //This signifies a selection was cleared. We don't want to store that as a range.
            continue;
        }
        ranges.add(new ArrayList<Integer>(Arrays.asList(start, end)));
    }
    editorManager.changeSelection(path, ranges, !isListening.get());
}
 
Example 5
Source File: TemplateLineStartEndHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
protected void doExecute(Editor editor, @Nullable Caret caret, DataContext dataContext) {
  final TemplateState templateState = TemplateManagerImpl.getTemplateState(editor);
  if (templateState != null && !templateState.isFinished()) {
    final TextRange range = templateState.getCurrentVariableRange();
    final int caretOffset = editor.getCaretModel().getOffset();
    if (range != null && shouldStayInsideVariable(range, caretOffset)) {
      int selectionOffset = editor.getSelectionModel().getLeadSelectionOffset();
      int offsetToMove = myIsHomeHandler ? range.getStartOffset() : range.getEndOffset();
      LogicalPosition logicalPosition = editor.offsetToLogicalPosition(offsetToMove).leanForward(myIsHomeHandler);
      editor.getCaretModel().moveToLogicalPosition(logicalPosition);
      EditorModificationUtil.scrollToCaret(editor);
      if (myWithSelection) {
        editor.getSelectionModel().setSelection(selectionOffset, offsetToMove);
      }
      else {
        editor.getSelectionModel().removeSelection();
      }
      return;
    }
  }
  myOriginalHandler.execute(editor, caret, dataContext);
}
 
Example 6
Source File: LineMarkerInfo.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a line marker info for the element.
 *
 * @param element         the element for which the line marker is created.
 * @param range           the range (relative to beginning of file) with which the marker is associated
 * @param icon            the icon to show in the gutter for the line marker
 * @param updatePass      the ID of the daemon pass during which the marker should be recalculated
 * @param tooltipProvider the callback to calculate the tooltip for the gutter icon
 * @param navHandler      the handler executed when the gutter icon is clicked
 */
public LineMarkerInfo(@Nonnull T element,
                      @Nonnull TextRange range,
                      Image icon,
                      int updatePass,
                      @Nullable Function<? super T, String> tooltipProvider,
                      @Nullable GutterIconNavigationHandler<T> navHandler,
                      @Nonnull GutterIconRenderer.Alignment alignment) {
  myIcon = icon;
  myTooltipProvider = tooltipProvider;
  myIconAlignment = alignment;
  elementRef = SmartPointerManager.getInstance(element.getProject()).createSmartPsiElementPointer(element);
  myNavigationHandler = navHandler;
  startOffset = range.getStartOffset();
  endOffset = range.getEndOffset();
  this.updatePass = 11; //Pass.LINE_MARKERS;
}
 
Example 7
Source File: PropertyEditorPanel.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
static boolean insideVisibleArea(Editor e, TextRange r) {
  final int textLength = e.getDocument().getTextLength();
  if (r.getStartOffset() > textLength) return false;
  if (r.getEndOffset() > textLength) return false;
  final Rectangle visibleArea = e.getScrollingModel().getVisibleArea();
  final Point point = e.logicalPositionToXY(e.offsetToLogicalPosition(r.getStartOffset()));

  return visibleArea.contains(point);
}
 
Example 8
Source File: IssueOutputFilter.java    From intellij with Apache License 2.0 5 votes vote down vote up
/**
 * A user-visible hyperlink navigating from the console to the relevant file + line of the issue.
 */
@Nullable
private static ResultItem hyperlinkItem(IssueOutput issue, int offset) {
  TextRange range = issue.getConsoleHyperlinkRange();
  HyperlinkInfo link = getHyperlinkInfo(issue);
  if (range == null || link == null) {
    return null;
  }
  return new ResultItem(range.getStartOffset() + offset, range.getEndOffset() + offset, link);
}
 
Example 9
Source File: FragmentListImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
public Fragment getFragmentAt(int offset, FragmentSide side, Condition<Fragment> condition) {
  for (Iterator<Fragment> iterator = iterator(); iterator.hasNext();) {
    Fragment fragment = iterator.next();
    TextRange range = fragment.getRange(side);
    if (range.getStartOffset() <= offset &&
        range.getEndOffset() > offset &&
        condition.value(fragment)) return fragment.getSubfragmentAt(offset, side, condition);
  }
  return null;
}
 
Example 10
Source File: HighlightUsagesHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void clearHighlights(Editor editor,
                                    HighlightManager highlightManager,
                                    List<TextRange> rangesToHighlight,
                                    TextAttributes attributes) {
  if (editor instanceof EditorWindow) editor = ((EditorWindow)editor).getDelegate();
  RangeHighlighter[] highlighters = ((HighlightManagerImpl)highlightManager).getHighlighters(editor);
  Arrays.sort(highlighters, (o1, o2) -> o1.getStartOffset() - o2.getStartOffset());
  Collections.sort(rangesToHighlight, (o1, o2) -> o1.getStartOffset() - o2.getStartOffset());
  int i = 0;
  int j = 0;
  while (i < highlighters.length && j < rangesToHighlight.size()) {
    RangeHighlighter highlighter = highlighters[i];
    TextRange highlighterRange = TextRange.create(highlighter);
    TextRange refRange = rangesToHighlight.get(j);
    if (refRange.equals(highlighterRange) && attributes.equals(highlighter.getTextAttributes()) &&
        highlighter.getLayer() == HighlighterLayer.SELECTION - 1) {
      highlightManager.removeSegmentHighlighter(editor, highlighter);
      i++;
    }
    else if (refRange.getStartOffset() > highlighterRange.getEndOffset()) {
      i++;
    }
    else if (refRange.getEndOffset() < highlighterRange.getStartOffset()) {
      j++;
    }
    else {
      i++;
      j++;
    }
  }
}
 
Example 11
Source File: XQueryFunctionDeclarationRangeHandler.java    From intellij-xquery with Apache License 2.0 5 votes vote down vote up
@NotNull
@Override
public TextRange getDeclarationRange(@NotNull XQueryFunctionDecl functionDeclaration) {
    PsiElement endElement = functionDeclaration.getFunctionBody();
    final TextRange textRange = functionDeclaration.getTextRange();
    int startOffset = textRange != null ? textRange.getStartOffset() : functionDeclaration.getTextOffset();
    int endOffset = endElement.getTextRange().getStartOffset();
    return new TextRange(startOffset, endOffset);
}
 
Example 12
Source File: FragmentedEditorHighlighter.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void translate(HighlighterIterator iterator, List<TextRange> ranges) {
  if (iterator.atEnd()) return;
  int offset = 0;
  for (TextRange range : ranges) {
    while (range.getStartOffset() > iterator.getStart()) {
      iterator.advance();
      if (iterator.atEnd()) return;
    }
    while (range.getEndOffset() >= iterator.getEnd()) {
      int relativeStart = iterator.getStart() - range.getStartOffset();
      boolean merged = false;
      if (myMergeByTextAttributes && ! myPieces.isEmpty()) {
        final Integer first = myPieces.descendingKeySet().first();
        final Element element = myPieces.get(first);
        if (element.getEnd() >= offset + relativeStart && myPieces.get(first).getAttributes().equals(iterator.getTextAttributes())) {
          // merge
          merged = true;
          myPieces.put(element.getStart(), new Element(element.getStart(),
                                                       offset + (iterator.getEnd() - range.getStartOffset()), iterator.getTokenType(),
                                                       iterator.getTextAttributes()));
        }
      }
      if (! merged) {
        myPieces.put(offset + relativeStart, new Element(offset + relativeStart,
                                                         offset + (iterator.getEnd() - range.getStartOffset()), iterator.getTokenType(),
                                                         iterator.getTextAttributes()));
      }
      iterator.advance();
      if (iterator.atEnd()) return;
    }
    offset += range.getLength() + 1 + myAdditionalOffset;  // myAdditionalOffset because of extra line - for shoene separators
  }
}
 
Example 13
Source File: PathReferenceManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static PsiReference[] mergeReferences(PsiElement element, List<PsiReference> references) {
  if (references.size() <= 1) {
    return references.toArray(new PsiReference[references.size()]);
  }
  Collections.sort(references, START_OFFSET_COMPARATOR);
  final List<PsiReference> intersecting = new ArrayList<PsiReference>();
  final List<PsiReference> notIntersecting = new ArrayList<PsiReference>();
  TextRange intersectingRange = references.get(0).getRangeInElement();
  boolean intersected = false;
  for (int i = 1; i < references.size(); i++) {
    final PsiReference reference = references.get(i);
    final TextRange range = reference.getRangeInElement();
    final int offset = range.getStartOffset();
    if (intersectingRange.getStartOffset() <= offset && intersectingRange.getEndOffset() >= offset) {
      intersected = true;
      intersecting.add(references.get(i - 1));
      if (i == references.size() - 1) {
        intersecting.add(reference);
      }
      intersectingRange = intersectingRange.union(range);
    } else {
      if (intersected) {
        intersecting.add(references.get(i - 1));
        intersected = false;
      } else {
        notIntersecting.add(references.get(i - 1));
      }
      intersectingRange = range;
      if (i == references.size() - 1) {
        notIntersecting.add(reference);
      }
    }
  }

  List<PsiReference> result = doMerge(element, intersecting);
  result.addAll(notIntersecting);

  return result.toArray(new PsiReference[result.size()]);
}
 
Example 14
Source File: PathReferenceManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static TextRange addIntersectingReferences(List<PsiReference> set, List<PsiReference> toAdd, TextRange range) {
  int startOffset = range.getStartOffset();
  int endOffset = range.getStartOffset();
  for (Iterator<PsiReference> iterator = set.iterator(); iterator.hasNext();) {
    PsiReference reference = iterator.next();
    final TextRange rangeInElement = reference.getRangeInElement();
    if (intersect(range, rangeInElement)) {
      toAdd.add(reference);
      iterator.remove();
      startOffset = Math.min(startOffset, rangeInElement.getStartOffset());
      endOffset = Math.max(endOffset, rangeInElement.getEndOffset());
    }
  }
  return new TextRange(startOffset, endOffset);
}
 
Example 15
Source File: LineFragment.java    From consulo with Apache License 2.0 5 votes vote down vote up
static TextRange shiftRange(TextRange shift, TextRange range) {
  int start = shift.getStartOffset();
  int newEnd = start + range.getEndOffset();
  int newStart = start + range.getStartOffset();
  LOG.assertTrue(newStart <= shift.getEndOffset());
  LOG.assertTrue(newEnd <= shift.getEndOffset());
  return new TextRange(newStart, newEnd);
}
 
Example 16
Source File: FileReferenceSet.java    From consulo with Apache License 2.0 5 votes vote down vote up
public FileReferenceSet(@Nonnull final PsiElement element) {
  myElement = element;
  TextRange range = ElementManipulators.getValueTextRange(element);
  myStartInElement = range.getStartOffset();
  myPathStringNonTrimmed = range.substring(element.getText());
  myPathString = myPathStringNonTrimmed.trim();
  myEndingSlashNotAllowed = true;
  myCaseSensitive = false;

  reparse();
}
 
Example 17
Source File: CommentByBlockCommentHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
private int doBoundCommentingAndGetShift(int offset, String commented, int skipLength, String toInsert, boolean skipBrace, TextRange selection) {
  if (commented == null && (offset == selection.getStartOffset() || offset + (skipBrace ? skipLength : 0) == selection.getEndOffset())) {
    return 0;
  }
  if (commented == null) {
    myDocument.insertString(offset + (skipBrace ? skipLength : 0), toInsert);
    return toInsert.length();
  }
  else {
    myDocument.replaceString(offset, offset + skipLength, commented);
    return commented.length() - skipLength;
  }
}
 
Example 18
Source File: DiffDrawUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
public List<RangeHighlighter> done() {
  List<RangeHighlighter> highlighters = new ArrayList<>();

  boolean isEmptyRange = startLine == endLine;
  boolean isLastLine = endLine == getLineCount(editor.getDocument());

  TextRange offsets = DiffUtil.getLinesRange(editor.getDocument(), startLine, endLine);
  int start = offsets.getStartOffset();
  int end = offsets.getEndOffset();

  TextAttributes attributes = isEmptyRange || resolved ? null : getTextAttributes(type, editor, ignored);
  TextAttributes stripeAttributes = isEmptyRange || resolved ? null : getStripeTextAttributes(type, editor);

  RangeHighlighter highlighter = editor.getMarkupModel()
          .addRangeHighlighter(start, end, DEFAULT_LAYER, attributes, HighlighterTargetArea.LINES_IN_RANGE);
  highlighters.add(highlighter);

  highlighter.setLineMarkerRenderer(new DiffLineMarkerRenderer(highlighter, type, ignored, resolved,
                                                               hideWithoutLineNumbers, isEmptyRange, isLastLine));

  if (isEmptyRange) {
    if (startLine == 0) {
      highlighters.addAll(createLineMarker(editor, 0, type, SeparatorPlacement.TOP, true, resolved, false));
    }
    else {
      highlighters.addAll(createLineMarker(editor, startLine - 1, type, SeparatorPlacement.BOTTOM, true, resolved, false));
    }
  }
  else if (resolved) {
    highlighters.addAll(createLineMarker(editor, startLine, type, SeparatorPlacement.TOP, false, resolved, false));
    highlighters.addAll(createLineMarker(editor, endLine - 1, type, SeparatorPlacement.BOTTOM, false, resolved, false));
  }

  if (stripeAttributes != null) {
    RangeHighlighter stripeHighlighter = editor.getMarkupModel()
            .addRangeHighlighter(start, end, STRIPE_LAYER, stripeAttributes, HighlighterTargetArea.LINES_IN_RANGE);
    highlighters.add(stripeHighlighter);
  }

  return highlighters;
}
 
Example 19
Source File: DocumentBasedFormattingModel.java    From consulo with Apache License 2.0 4 votes vote down vote up
private int shiftIndentInside(final TextRange elementRange, final int shift) {
  final StringBuilder buffer = new StringBuilder();
  StringBuilder afterWhiteSpace = new StringBuilder();
  int whiteSpaceLength = 0;
  boolean insideWhiteSpace = true;
  int line = 0;
  for (int i = elementRange.getStartOffset(); i < elementRange.getEndOffset(); i++) {
    final char c = myDocument.getCharsSequence().charAt(i);
    switch (c) {
      case '\n':
        if (line > 0) {
          createWhiteSpace(whiteSpaceLength + shift, buffer);
        }
        buffer.append(afterWhiteSpace.toString());
        insideWhiteSpace = true;
        whiteSpaceLength = 0;
        afterWhiteSpace = new StringBuilder();
        buffer.append(c);
        line++;
        break;
      case ' ':
        if (insideWhiteSpace) {
          whiteSpaceLength += 1;
        }
        else {
          afterWhiteSpace.append(c);
        }
        break;
      case '\t':
        if (insideWhiteSpace) {
          whiteSpaceLength += getIndentOptions().TAB_SIZE;
        }
        else {
          afterWhiteSpace.append(c);
        }

        break;
      default:
        insideWhiteSpace = false;
        afterWhiteSpace.append(c);
    }
  }
  if (line > 0) {
    createWhiteSpace(whiteSpaceLength + shift, buffer);
  }
  buffer.append(afterWhiteSpace.toString());
  myDocument.replaceString(elementRange.getStartOffset(), elementRange.getEndOffset(), buffer.toString());
  return buffer.length();
}
 
Example 20
Source File: EclipseRegionAdapter.java    From spring-javaformat with Apache License 2.0 4 votes vote down vote up
public EclipseRegionAdapter(TextRange range) {
	super(range.getStartOffset(), range.getLength());
}