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

The following examples show how to use com.intellij.openapi.util.TextRange#getEndOffset() . 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
public void replaceElementText(final TextRange range, final String text, final StripSpaces strips) {
  if (range == null) return;
  int start = range.getStartOffset();
  int end = range.getEndOffset();
  String documentText = document.getText();

  if (strips.after) {
   while (end < documentText.length() && HaxeCharUtils.isSpace(documentText.charAt(end))) {
      end++;
    }
  }
  if (strips.before) {
    while (start > 0 && HaxeCharUtils.isSpace(documentText.charAt(start - 1))) {
      start--;
    }
  }
  replaceAndFormat(new TextRange(start, end), text);
}
 
Example 2
Source File: PsiDynaReference.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public TextRange getRangeInElement() {

  PsiReference resolved = null;
  PsiReference reference = myReferences.get(0);

  if (reference.resolve() != null) {
    resolved = reference;
  }

  final TextRange range = reference.getRangeInElement();
  int start = range.getStartOffset();
  int end = range.getEndOffset();
  for (int i = 1; i < myReferences.size(); i++) {
    reference = myReferences.get(i);
    final TextRange textRange = getRange(reference);
    start = Math.min(start, textRange.getStartOffset());
    if (resolved == null) {
      end = Math.max(end, textRange.getEndOffset());
    }
  }
  return new TextRange(start, end);
}
 
Example 3
Source File: CSharpDeclarationMover.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@RequiredReadAction
private static LineRange memberRange(@Nonnull PsiElement member, Editor editor, LineRange lineRange)
{
	final TextRange textRange = member.getTextRange();
	if(editor.getDocument().getTextLength() < textRange.getEndOffset())
	{
		return null;
	}
	final int startLine = editor.offsetToLogicalPosition(textRange.getStartOffset()).line;
	final int endLine = editor.offsetToLogicalPosition(textRange.getEndOffset()).line + 1;
	if(!isInsideDeclaration(member, startLine, endLine, lineRange, editor))
	{
		return null;
	}

	return new LineRange(startLine, endLine);
}
 
Example 4
Source File: PsiTreeUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
public static <T extends PsiElement> T findElementOfClassAtOffset(@Nonnull PsiFile file, int offset, @Nonnull Class<T> clazz, boolean strictStart) {
  final List<PsiFile> psiRoots = file.getViewProvider().getAllFiles();
  T result = null;
  for (PsiElement root : psiRoots) {
    final PsiElement elementAt = root.findElementAt(offset);
    if (elementAt != null) {
      final T parent = getParentOfType(elementAt, clazz, strictStart);
      if (parent != null) {
        final TextRange range = parent.getTextRange();
        if (!strictStart || range.getStartOffset() == offset) {
          if (result == null || result.getTextRange().getEndOffset() > range.getEndOffset()) {
            result = parent;
          }
        }
      }
    }
  }

  return result;
}
 
Example 5
Source File: TextRangeUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * Excludes ranges from the original range. For example, if the original range is [30..100] and ranges to exclude are
 * [20..50] and [60..90], resulting ranges will be [50..60] and [90..100]. The ranges may overlap and follow in any order. In the latter
 * case the original list of excluded ranges is sorted by start/end offset.
 *
 * @param original       The original range to exclude the ranges from.
 * @param excludedRanges The list of ranges to exclude.
 * @return A list of ranges after excluded ranges have been applied.
 */
public static Iterable<TextRange> excludeRanges(@Nonnull TextRange original, @Nonnull List<? extends TextRange> excludedRanges) {
  if (!excludedRanges.isEmpty()) {
    if (excludedRanges.size() > 1) {
      excludedRanges.sort(RANGE_COMPARATOR);
    }
    int enabledRangeStart = original.getStartOffset();
    List<TextRange> enabledRanges = new ArrayList<>();
    for (TextRange excludedRange : excludedRanges) {
      if (excludedRange.getEndOffset() < enabledRangeStart) continue;
      int excludedRangeStart = excludedRange.getStartOffset();
      if (excludedRangeStart > original.getEndOffset()) break;
      if (excludedRangeStart > enabledRangeStart) {
        enabledRanges.add(new TextRange(enabledRangeStart, excludedRangeStart));
      }
      enabledRangeStart = excludedRange.getEndOffset();
    }
    if (enabledRangeStart < original.getEndOffset()) {
      enabledRanges.add(new TextRange(enabledRangeStart, original.getEndOffset()));
    }
    return enabledRanges;
  }
  return Collections.singletonList(original);
}
 
Example 6
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 7
Source File: ProblemDescriptorBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
public TextRange getTextRange() {
  PsiElement startElement = getStartElement();
  PsiElement endElement = myEndSmartPointer == null ? startElement : getEndElement();
  if (startElement == null || endElement == null) {
    return null;
  }

  TextRange textRange = startElement.getTextRange();
  if (startElement == endElement) {
    if (isAfterEndOfLine()) return new TextRange(textRange.getEndOffset(), textRange.getEndOffset());
    if (myTextRangeInElement != null) {
      return new TextRange(textRange.getStartOffset() + myTextRangeInElement.getStartOffset(),
                           textRange.getStartOffset() + myTextRangeInElement.getEndOffset());
    }
    return textRange;
  }
  return new TextRange(textRange.getStartOffset(), endElement.getTextRange().getEndOffset());
}
 
Example 8
Source File: DesktopSelectionModelImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
void fireSelectionChanged(SelectionEvent event) {
  TextRange[] oldRanges = event.getOldRanges();
  TextRange[] newRanges = event.getNewRanges();
  int count = Math.min(oldRanges.length, newRanges.length);
  for (int i = 0; i < count; i++) {
    TextRange oldRange = oldRanges[i];
    TextRange newRange = newRanges[i];
    int oldSelectionStart = oldRange.getStartOffset();
    int startOffset = newRange.getStartOffset();
    int oldSelectionEnd = oldRange.getEndOffset();
    int endOffset = newRange.getEndOffset();
    myEditor.repaint(Math.min(oldSelectionStart, startOffset), Math.max(oldSelectionStart, startOffset), false);
    myEditor.repaint(Math.min(oldSelectionEnd, endOffset), Math.max(oldSelectionEnd, endOffset), false);
  }
  TextRange[] remaining = oldRanges.length < newRanges.length ? newRanges : oldRanges;
  for (int i = count; i < remaining.length; i++) {
    TextRange range = remaining[i];
    myEditor.repaint(range.getStartOffset(), range.getEndOffset(), false);
  }

  broadcastSelectionEvent(event);
}
 
Example 9
Source File: NaturalLanguageTextSelectioner.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private static TextRange expandSelection(PsiElement e, CharSequence editorText, int selStart, int selEnd) {
  TextRange range = e.getTextRange();
  int shift = range.getStartOffset();
  if (selStart <= shift || selEnd >= range.getEndOffset()) {
    return null;
  }

  String elementText = editorText.subSequence(shift, range.getEndOffset()).toString();
  int start = selStart - shift;
  int end = selEnd - shift;

  TextRange best = findSentenceRange(elementText, start, end);
  best = narrowRange(best, findCustomRange(elementText, start, end, '\"', '\"'));
  best = narrowRange(best, findCustomRange(elementText, start, end, '(', ')'));
  best = narrowRange(best, findCustomRange(elementText, start, end, '<', '>'));
  best = narrowRange(best, findCustomRange(elementText, start, end, '[', ']'));

  TextRange natural = findNaturalRange(elementText, start, end);
  if (!natural.contains(best)) {
    return null;
  }

  TextRange paragraph = findParagraphRange(elementText, start, end);
  if (best.getStartOffset() == start && best.getEndOffset() == end || !paragraph.contains(best)) {
    return paragraph.shiftRight(shift);
  }


  return best.shiftRight(shift);
}
 
Example 10
Source File: BlockRangesMap.java    From consulo with Apache License 2.0 5 votes vote down vote up
public boolean containsLineFeeds(final TextRange dependency) {
  LeafBlockWrapper child = myTextRangeToWrapper.get(dependency.getStartOffset());
  if (child == null) return false;
  if (child.containsLineFeeds()) return true;
  final int endOffset = dependency.getEndOffset();
  while (child.getEndOffset() < endOffset) {
    child = child.getNextBlock();
    if (child == null) return false;
    if (child.getWhiteSpace().containsLineFeeds()) return true;
    if (child.containsLineFeeds()) return true;
  }
  return false;
}
 
Example 11
Source File: FormattingRangesExtender.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private TextRange trimSpaces(@Nonnull TextRange range) {
  int startOffset = range.getStartOffset();
  int endOffset = range.getEndOffset();
  startOffset = CharArrayUtil.shiftForward(myDocument.getCharsSequence(), startOffset, endOffset, " /t");
  if (startOffset == endOffset) return null;
  endOffset = CharArrayUtil.shiftBackward(myDocument.getCharsSequence(), startOffset, endOffset, " /t");
  return new TextRange(startOffset, endOffset);
}
 
Example 12
Source File: GraphQLLanguageInjectionUtil.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
public static TextRange getGraphQLTextRange(JSStringTemplateExpression template) {
    int start = 0;
    int end = 0;
    final TextRange[] stringRanges = template.getStringRanges();
    for (TextRange textRange : stringRanges) {
        if (start == 0) {
            start = textRange.getStartOffset();
        }
        end = textRange.getEndOffset();
    }
    return TextRange.create(start, end);
}
 
Example 13
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 14
Source File: PsiBasedFormattingModel.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private String replaceWithPSI(final TextRange textRange, final String whiteSpace) {
  final int offset = textRange.getEndOffset();
  ASTNode leafElement = findElementAt(offset);

  if (leafElement != null) {
    PsiFile hostFile = myASTNode.getPsi().getContainingFile();
    TextRange effectiveRange = textRange;
    List<DocumentWindow> injections = InjectedLanguageManager.getInstance(hostFile.getProject()).getCachedInjectedDocumentsInRange(hostFile, TextRange.from(offset, 0));
    if (!injections.isEmpty()) {
      PsiElement injectedElement = PsiDocumentManager.getInstance(myProject).getPsiFile(injections.get(0));
      PsiLanguageInjectionHost host = InjectedLanguageUtil.findInjectionHost(injectedElement);
      TextRange corrected = host == null ? null : correctRangeByInjection(textRange, host);
      if (corrected != null) {
        effectiveRange = corrected;
      }
    }

    if (leafElement.getPsi() instanceof PsiFile) {
      return null;
    }
    else {
      LOG.assertTrue(leafElement.getPsi().isValid());
      return replaceWithPsiInLeaf(effectiveRange, whiteSpace, leafElement);
    }
  }
  else if (textRange.getEndOffset() == myASTNode.getTextLength()) {
    CodeStyleManager.getInstance(myProject).performActionWithFormatterDisabled((Runnable)() -> FormatterUtil.replaceLastWhiteSpace(myASTNode, whiteSpace, textRange));
    return whiteSpace;
  }
  else {
    return null;
  }
}
 
Example 15
Source File: CompletionAssertions.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Contract("_,_,_,null->fail")
static void assertCompletionPositionPsiConsistent(OffsetsInFile offsets, int offset, PsiFile originalFile, PsiElement insertedElement) {
  PsiFile fileCopy = offsets.getFile();
  if (insertedElement == null) {
    throw new RuntimeExceptionWithAttachments("No element at insertion offset", "offset=" + offset, createFileTextAttachment(fileCopy, originalFile), createAstAttachment(fileCopy, originalFile));
  }

  final TextRange range = insertedElement.getTextRange();
  CharSequence fileCopyText = fileCopy.getViewProvider().getContents();
  if ((range.getEndOffset() > fileCopyText.length()) || !isEquals(fileCopyText.subSequence(range.getStartOffset(), range.getEndOffset()), insertedElement.getNode().getChars())) {
    throw new RuntimeExceptionWithAttachments("Inconsistent completion tree", "range=" + range, createFileTextAttachment(fileCopy, originalFile), createAstAttachment(fileCopy, originalFile),
                                              new Attachment("Element at caret.txt", insertedElement.getText()));
  }
}
 
Example 16
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 17
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 18
Source File: PsiUtilBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
public static Language reallyEvaluateLanguageInRange(final int start, final int end, @Nonnull PsiFile file) {
  if (file instanceof PsiBinaryFile) {
    return file.getLanguage();
  }
  Language lang = null;
  int curOffset = start;
  do {
    PsiElement elt = getElementAtOffset(file, curOffset);

    if (!(elt instanceof PsiWhiteSpace)) {
      final Language language = findLanguageFromElement(elt);
      if (lang == null) {
        lang = language;
      }
      else if (lang != language) {
        return null;
      }
    }
    TextRange range = elt.getTextRange();
    if (range == null) {
      LOG.error("Null range for element " + elt + " of " + elt.getClass() + " in file " + file + " at offset " + curOffset);
      return file.getLanguage();
    }
    int endOffset = range.getEndOffset();
    curOffset = endOffset <= curOffset ? curOffset + 1 : endOffset;
  }
  while (curOffset < end);
  return narrowLanguage(lang, file.getLanguage());
}
 
Example 19
Source File: BlockUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static List<Block> mergeBlocks(@Nonnull List<TemplateLanguageBlock> tlBlocks, @Nonnull List<DataLanguageBlockWrapper> foreignBlocks) {
  ArrayList<Block> result = new ArrayList<Block>(tlBlocks.size() + foreignBlocks.size());
  int vInd = 0;
  int fInd = 0;
  while (vInd < tlBlocks.size() && fInd < foreignBlocks.size()) {
    final TemplateLanguageBlock v = tlBlocks.get(vInd);
    final DataLanguageBlockWrapper f = foreignBlocks.get(fInd);
    final TextRange vRange = v.getTextRange();
    final TextRange fRange = f.getTextRange();
    if (vRange.getStartOffset() >= fRange.getEndOffset()) {
      // add leading foreign blocks
      result.add(f);
      fInd++;
    }
    else if (vRange.getEndOffset() <= fRange.getStartOffset()) {
      // add leading TL blocks
      result.add(v);
      vInd++;
    }
    else if (vRange.getStartOffset() < fRange.getStartOffset() ||
             vRange.getStartOffset() == fRange.getStartOffset() && vRange.getEndOffset() >= fRange.getEndOffset()) {
      // add including TL blocks and split intersecting foreign blocks
      result.add(v);
      while (fInd < foreignBlocks.size() && vRange.contains(foreignBlocks.get(fInd).getTextRange())) {
        v.addForeignChild(foreignBlocks.get(fInd++));
      }
      if (fInd < foreignBlocks.size()) {
        final DataLanguageBlockWrapper notContainedF = foreignBlocks.get(fInd);
        if (vRange.intersectsStrict(notContainedF.getTextRange())) {
          Pair<List<DataLanguageBlockWrapper>, List<DataLanguageBlockWrapper>> splitBlocks = splitBlocksByRightBound(notContainedF.getOriginal(), vRange);
          v.addForeignChildren(splitBlocks.getFirst());
          foreignBlocks.remove(fInd);
          if (splitBlocks.getSecond().size() > 0) {
            foreignBlocks.addAll(fInd, splitBlocks.getSecond());
          }
        }
      }
      vInd++;
    }
    else if (vRange.getStartOffset() > fRange.getStartOffset() ||
             vRange.getStartOffset() == fRange.getStartOffset() && vRange.getEndOffset() < fRange.getEndOffset()) {
      // add including foreign blocks or split them if needed
      int lastContainedTlInd = vInd;
      while (lastContainedTlInd < tlBlocks.size() && fRange.intersectsStrict(tlBlocks.get(lastContainedTlInd).getTextRange())) {
        lastContainedTlInd++;
      }
      if (fRange.contains(tlBlocks.get(lastContainedTlInd - 1).getTextRange())) {
        result.add(f);
        fInd++;
        while (vInd < lastContainedTlInd) {
          f.addTlChild(tlBlocks.get(vInd++));
        }
      }
      else {
        foreignBlocks.remove(fInd);
        foreignBlocks.addAll(fInd, buildChildWrappers(f.getOriginal()));
      }
    }
  }
  while (vInd < tlBlocks.size()) {
    result.add(tlBlocks.get(vInd++));
  }
  while (fInd < foreignBlocks.size()) {
    result.add(foreignBlocks.get(fInd++));
  }
  return result;
}
 
Example 20
Source File: UpdateFoldRegionsOperation.java    From consulo with Apache License 2.0 4 votes vote down vote up
private List<FoldRegion> addNewRegions(@Nonnull EditorFoldingInfo info,
                                       @Nonnull FoldingModelEx foldingModel,
                                       @Nonnull Map<TextRange, Boolean> rangeToExpandStatusMap,
                                       @Nonnull Map<FoldRegion, Boolean> shouldExpand,
                                       @Nonnull Map<FoldingGroup, Boolean> groupExpand) {
  List<FoldRegion> newRegions = new ArrayList<>();
  SmartPointerManager smartPointerManager = SmartPointerManager.getInstance(myProject);
  for (FoldingUpdate.RegionInfo regionInfo : myRegionInfos) {
    ProgressManager.checkCanceled();
    FoldingDescriptor descriptor = regionInfo.descriptor;
    FoldingGroup group = descriptor.getGroup();
    TextRange range = descriptor.getRange();
    String placeholder = null;
    try {
      placeholder = descriptor.getPlaceholderText();
    }
    catch (IndexNotReadyException ignore) {
    }
    if (range.getEndOffset() > myEditor.getDocument().getTextLength()) {
      LOG.error(String.format("Invalid folding descriptor detected (%s). It ends beyond the document range (%d)", descriptor, myEditor.getDocument().getTextLength()));
      continue;
    }
    FoldRegion region = foldingModel.createFoldRegion(range.getStartOffset(), range.getEndOffset(), placeholder == null ? "..." : placeholder, group, descriptor.isNonExpandable());
    if (region == null) continue;

    if (descriptor.isNonExpandable()) region.putUserData(FoldingModelImpl.SELECT_REGION_ON_CARET_NEARBY, Boolean.TRUE);

    PsiElement psi = descriptor.getElement().getPsi();

    if (psi == null || !psi.isValid() || !myFile.isValid()) {
      region.dispose();
      continue;
    }

    region.setGutterMarkEnabledForSingleLine(descriptor.isGutterMarkEnabledForSingleLine());

    if (descriptor.canBeRemovedWhenCollapsed()) region.putUserData(CAN_BE_REMOVED_WHEN_COLLAPSED, Boolean.TRUE);
    region.putUserData(COLLAPSED_BY_DEFAULT, regionInfo.collapsedByDefault);
    region.putUserData(SIGNATURE, ObjectUtils.chooseNotNull(regionInfo.signature, NO_SIGNATURE));

    info.addRegion(region, smartPointerManager.createSmartPsiElementPointer(psi));
    newRegions.add(region);

    boolean expandStatus = !descriptor.isNonExpandable() && shouldExpandNewRegion(range, rangeToExpandStatusMap, regionInfo.collapsedByDefault);
    if (group == null) {
      shouldExpand.put(region, expandStatus);
    }
    else {
      final Boolean alreadyExpanded = groupExpand.get(group);
      groupExpand.put(group, alreadyExpanded == null ? expandStatus : alreadyExpanded.booleanValue() || expandStatus);
    }
  }

  return newRegions;
}