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

The following examples show how to use com.intellij.openapi.util.TextRange#intersection() . 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: PhpHighlightPackParametersUsagesHandler.java    From idea-php-advanced-autocomplete with MIT License 6 votes vote down vote up
@NotNull
private static HashMap<Integer, RelativeRange> getRelativeSpecificationRanges(HashMap<Integer, PhpPackFormatSpecificationParser.PackSpecification> specifications, List<StringLiteralExpression> targets) {
    Map<TextRange, StringLiteralExpression> rangesInsideResultingFormatString = getRangesWithExpressionInsideResultingFormatString(targets);
    HashMap<Integer, RelativeRange> result = new HashMap<>();

    for (Map.Entry<Integer, PhpPackFormatSpecificationParser.PackSpecification> entry : specifications.entrySet()) {
        PhpPackFormatSpecificationParser.PackSpecification specification = entry.getValue();
        for (Map.Entry<TextRange, StringLiteralExpression> e : rangesInsideResultingFormatString.entrySet()) {
            TextRange expressionRangeInsideFormatString = e.getKey();
            TextRange specificationRangeInsideFormatString = expressionRangeInsideFormatString.intersection(specification.getRangeInElement());
            if (specificationRangeInsideFormatString != null && !specificationRangeInsideFormatString.isEmpty()) {
                result.put(entry.getKey(), new RelativeRange(e.getValue(), specificationRangeInsideFormatString.shiftLeft(expressionRangeInsideFormatString.getStartOffset())));
            }
        }
    }

    return result;
}
 
Example 2
Source File: ShredImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private TextRange calcRangeInsideHostElement(boolean usePsiRange) {
  PsiLanguageInjectionHost host = getHost();
  Segment psiRange = usePsiRange ? relevantRangeInHost.getPsiRange() : relevantRangeInHost.getRange();
  TextRange textRange = psiRange == null ? null : TextRange.create(psiRange);
  if (host == null) {
    if (textRange != null) return textRange;
    Segment fromSP = usePsiRange ? hostElementPointer.getPsiRange() : hostElementPointer.getRange();
    if (fromSP != null) return TextRange.create(fromSP);
    return new TextRange(0, 0);
  }
  TextRange hostTextRange = host.getTextRange();
  textRange = textRange == null ? null : textRange.intersection(hostTextRange);
  if (textRange == null) return new ProperTextRange(0, hostTextRange.getLength());

  return textRange.shiftLeft(hostTextRange.getStartOffset());
}
 
Example 3
Source File: FileStatusMap.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * @param editor
 * @param passId
 * @return null means the file is clean
 */
@Nullable
// used in scala
public static TextRange getDirtyTextRange(@Nonnull Editor editor, int passId) {
  Document document = editor.getDocument();

  FileStatusMap me = DaemonCodeAnalyzerEx.getInstanceEx(editor.getProject()).getFileStatusMap();
  TextRange dirtyScope = me.getFileDirtyScope(document, passId);
  if (dirtyScope == null) return null;
  TextRange documentRange = TextRange.from(0, document.getTextLength());
  return documentRange.intersection(dirtyScope);
}
 
Example 4
Source File: CommentByBlockCommentHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
private boolean isWhiteSpaceOrComment(@Nonnull PsiElement element, @Nonnull TextRange range) {
  final TextRange textRange = element.getTextRange();
  TextRange intersection = range.intersection(textRange);
  if (intersection == null) {
    return false;
  }
  intersection = TextRange.create(Math.max(intersection.getStartOffset() - textRange.getStartOffset(), 0), Math.min(intersection.getEndOffset() - textRange.getStartOffset(), textRange.getLength()));
  return isWhiteSpaceOrComment(element) || intersection.substring(element.getText()).trim().length() == 0;
}
 
Example 5
Source File: DefaultHighlightInfoProcessor.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void highlightsInsideVisiblePartAreProduced(@Nonnull final HighlightingSession session,
                                                   @Nullable Editor editor,
                                                   @Nonnull final List<? extends HighlightInfo> infos,
                                                   @Nonnull TextRange priorityRange,
                                                   @Nonnull TextRange restrictRange,
                                                   final int groupId) {
  final PsiFile psiFile = session.getPsiFile();
  final Project project = psiFile.getProject();
  final Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile);
  if (document == null) return;
  final long modificationStamp = document.getModificationStamp();
  final TextRange priorityIntersection = priorityRange.intersection(restrictRange);
  List<? extends HighlightInfo> infoCopy = new ArrayList<>(infos);
  ((HighlightingSessionImpl)session).applyInEDT(() -> {
    if (modificationStamp != document.getModificationStamp()) return;
    if (priorityIntersection != null) {
      MarkupModel markupModel = DocumentMarkupModel.forDocument(document, project, true);

      EditorColorsScheme scheme = session.getColorsScheme();
      UpdateHighlightersUtil.setHighlightersInRange(project, document, priorityIntersection, scheme, infoCopy, (MarkupModelEx)markupModel, groupId);
    }
    if (editor != null && !editor.isDisposed()) {
      // usability: show auto import popup as soon as possible
      if (!DumbService.isDumb(project)) {
        ShowAutoImportPassFactory siFactory = TextEditorHighlightingPassFactory.EP_NAME.findExtensionOrFail(project, ShowAutoImportPassFactory.class);
        TextEditorHighlightingPass highlightingPass = siFactory.createHighlightingPass(psiFile, editor);
        if (highlightingPass != null) {
          highlightingPass.doApplyInformationToEditor();
        }
      }

      repaintErrorStripeAndIcon(editor, project);
    }
  });
}
 
Example 6
Source File: FoldingUpdate.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static boolean areConflicting(TextRange range1, TextRange range2) {
  if (range1.equals(range2)) return true;
  if (range1.contains(range2) || range2.contains(range1)) return false;

  TextRange intersection = range1.intersection(range2);
  return intersection != null && !intersection.isEmpty();
}
 
Example 7
Source File: InjectedLanguageBlockWrapper.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public TextRange getTextRange() {
  TextRange range = myOriginal.getTextRange();
  if (myRange != null) {
    range = range.intersection(myRange);
  }

  int start = myOffset + range.getStartOffset() - (myRange != null ? myRange.getStartOffset() : 0);
  return TextRange.from(start, range.getLength());
}
 
Example 8
Source File: NameSuggestionsField.java    From consulo with Apache License 2.0 5 votes vote down vote up
public NameSuggestionsField(final String[] suggestedNames, final Project project, final FileType fileType, @Nullable final Editor editor) {
  this(suggestedNames, project, fileType);
  if (editor == null) return;
  // later here because EditorTextField creates Editor during addNotify()
  final Runnable selectionRunnable = new Runnable() {
    @Override
    public void run() {
      final int offset = editor.getCaretModel().getOffset();
      List<TextRange> ranges = new ArrayList<TextRange>();
      SelectWordUtil.addWordSelection(editor.getSettings().isCamelWords(), editor.getDocument().getCharsSequence(), offset, ranges);
      Editor myEditor = getEditor();
      if (myEditor == null) return;
      for (TextRange wordRange : ranges) {
        String word = editor.getDocument().getText(wordRange);
        if (!word.equals(getEnteredName())) continue;
        final SelectionModel selectionModel = editor.getSelectionModel();
        myEditor.getSelectionModel().removeSelection();
        final int wordRangeStartOffset = wordRange.getStartOffset();
        int myOffset = offset - wordRangeStartOffset;
        myEditor.getCaretModel().moveToOffset(myOffset);
        TextRange selected = new TextRange(Math.max(0, selectionModel.getSelectionStart() - wordRangeStartOffset),
                                           Math.max(0, selectionModel.getSelectionEnd() - wordRangeStartOffset));
        selected = selected.intersection(new TextRange(0, myEditor.getDocument().getTextLength()));
        if (selectionModel.hasSelection() && selected != null && !selected.isEmpty()) {
          myEditor.getSelectionModel().setSelection(selected.getStartOffset(), selected.getEndOffset());
        }
        else if (shouldSelectAll()) {
          myEditor.getSelectionModel().setSelection(0, myEditor.getDocument().getTextLength());
        }
        break;
      }
    }
  };
  SwingUtilities.invokeLater(selectionRunnable);
}
 
Example 9
Source File: ParameterInfoComponent.java    From consulo with Apache License 2.0 4 votes vote down vote up
private String setup(String text,
                     Function<? super String, String> escapeFunction,
                     int highlightStartOffset,
                     int highlightEndOffset,
                     boolean isDisabled,
                     boolean strikeout,
                     boolean isDisabledBeforeHighlight,
                     Color background) {
  StringBuilder buf = new StringBuilder(text.length());
  setBackground(background);

  String[] lines = UIUtil.splitText(text, getFontMetrics(BOLD_FONT),
                                    // disable splitting by width, to avoid depending on platform's font in tests
                                    ApplicationManager.getApplication().isUnitTestMode() ? Integer.MAX_VALUE : myWidthLimit, ',');

  int lineOffset = 0;

  boolean hasHighlighting = highlightStartOffset >= 0 && highlightEndOffset > highlightStartOffset;
  TextRange highlightingRange = hasHighlighting ? new TextRange(highlightStartOffset, highlightEndOffset) : null;

  for (int i = 0; i < lines.length; i++) {
    String line = lines[i];
    OneLineComponent component = getOneLineComponent(i);

    TextRange lRange = new TextRange(lineOffset, lineOffset + line.length());
    TextRange hr = highlightingRange == null ? null : lRange.intersection(highlightingRange);
    hr = hr == null ? null : hr.shiftRight(-lineOffset);

    String before = escapeString(hr == null ? line : line.substring(0, hr.getStartOffset()), escapeFunction);
    String in = hr == null ? "" : escapeString(hr.substring(line), escapeFunction);
    String after = hr == null ? "" : escapeString(line.substring(hr.getEndOffset()), escapeFunction);

    TextRange escapedHighlightingRange = in.isEmpty() ? null : TextRange.create(before.length(), before.length() + in.length());
    buf.append(component.setup(before + in + after, isDisabled, strikeout, background, escapedHighlightingRange,
                               isDisabledBeforeHighlight && (highlightStartOffset < 0 || highlightEndOffset > lineOffset)));

    lineOffset += line.length();
  }
  trimComponents(lines.length);
  return buf.toString();
}
 
Example 10
Source File: InjectedLanguageManagerImpl.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * intersection may spread over several injected fragments
 *
 * @param rangeToEdit range in encoded(raw) PSI
 * @return list of ranges in encoded (raw) PSI
 */
@SuppressWarnings("ConstantConditions")
@Override
@Nonnull
public List<TextRange> intersectWithAllEditableFragments(@Nonnull PsiFile injectedPsi, @Nonnull TextRange rangeToEdit) {
  Place shreds = InjectedLanguageUtil.getShreds(injectedPsi);
  if (shreds == null) return Collections.emptyList();
  Object result = null; // optimization: TextRange or ArrayList
  int count = 0;
  int offset = 0;
  for (PsiLanguageInjectionHost.Shred shred : shreds) {
    TextRange encodedRange = TextRange.from(offset + shred.getPrefix().length(), shred.getRangeInsideHost().getLength());
    TextRange intersection = encodedRange.intersection(rangeToEdit);
    if (intersection != null) {
      count++;
      if (count == 1) {
        result = intersection;
      }
      else if (count == 2) {
        TextRange range = (TextRange)result;
        if (range.isEmpty()) {
          result = intersection;
          count = 1;
        }
        else if (intersection.isEmpty()) {
          count = 1;
        }
        else {
          List<TextRange> list = new ArrayList<>();
          list.add(range);
          list.add(intersection);
          result = list;
        }
      }
      else if (intersection.isEmpty()) {
        count--;
      }
      else {
        //noinspection unchecked
        ((List<TextRange>)result).add(intersection);
      }
    }
    offset += shred.getPrefix().length() + shred.getRangeInsideHost().getLength() + shred.getSuffix().length();
  }
  //noinspection unchecked
  return count == 0 ? Collections.emptyList() : count == 1 ? Collections.singletonList((TextRange)result) : (List<TextRange>)result;
}