com.intellij.openapi.editor.markup.HighlighterLayer Java Examples

The following examples show how to use com.intellij.openapi.editor.markup.HighlighterLayer. 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: CtrlMouseHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private HighlightersSet installHighlighterSet(@Nonnull Info info, @Nonnull EditorEx editor, boolean highlighterOnly) {
  editor.getContentComponent().addKeyListener(myEditorKeyListener);
  editor.getScrollingModel().addVisibleAreaListener(myVisibleAreaListener);
  if (info.isNavigatable()) {
    editor.setCustomCursor(CtrlMouseHandler.class, Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
  }

  List<RangeHighlighter> highlighters = new ArrayList<>();

  if (!highlighterOnly || info.isNavigatable()) {
    TextAttributes attributes = info.isNavigatable()
                                ? EditorColorsManager.getInstance().getGlobalScheme().getAttributes(EditorColors.REFERENCE_HYPERLINK_COLOR)
                                : new TextAttributes(null, HintUtil.getInformationColor(), null, null, Font.PLAIN);
    for (TextRange range : info.getRanges()) {
      TextAttributes attr = NavigationUtil.patchAttributesColor(attributes, range, editor);
      final RangeHighlighter highlighter = editor.getMarkupModel().addRangeHighlighter(range.getStartOffset(), range.getEndOffset(), HighlighterLayer.HYPERLINK, attr, HighlighterTargetArea.EXACT_RANGE);
      highlighters.add(highlighter);
    }
  }

  return new HighlightersSet(highlighters, editor, info);
}
 
Example #2
Source File: ApplyPatchChange.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
private MyGutterOperation createOperation(@Nonnull OperationType type) {
  if (isResolved()) return null;

  EditorEx editor = myViewer.getPatchEditor();
  Document document = editor.getDocument();

  int line = getPatchRange().start;
  int offset = line == DiffUtil.getLineCount(document) ? document.getTextLength() : document.getLineStartOffset(line);

  RangeHighlighter highlighter = editor.getMarkupModel().addRangeHighlighter(offset, offset,
                                                                             HighlighterLayer.ADDITIONAL_SYNTAX,
                                                                             null,
                                                                             HighlighterTargetArea.LINES_IN_RANGE);
  return new MyGutterOperation(highlighter, type);
}
 
Example #3
Source File: CommentsDiffTool.java    From Crucible4IDEA with MIT License 6 votes vote down vote up
private static void addGutter(@NotNull Editor editor2,
                              @NotNull final Review review,
                              @NotNull FilePath filePath,
                              @Nullable final ContentRevision revision) {
  if (revision == null) return;

  for (Comment comment : review.getComments()) {
    final String id = comment.getReviewItemId();
    final String path = review.getPathById(id);
    if (path != null && filePath.getPath().endsWith(path) &&
        (review.isInPatch(comment) || revision.getRevisionNumber().asString().equals(comment.getRevision()))) {

      int line = Integer.parseInt(comment.getLine()) - 1;
      final RangeHighlighter highlighter = editor2.getMarkupModel().addLineHighlighter(line, HighlighterLayer.ERROR + 1, null);
      final ReviewGutterIconRenderer gutterIconRenderer = new ReviewGutterIconRenderer(review, filePath, comment);
      highlighter.setGutterIconRenderer(gutterIconRenderer);
    }
  }
}
 
Example #4
Source File: ApplyPatchChange.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void createStatusHighlighter() {
  int line1 = myPatchDeletionRange.start;
  int line2 = myPatchInsertionRange.end;

  Color color = getStatusColor();
  if (isResolved()) {
    color = ColorUtil.mix(color, myViewer.getPatchEditor().getGutterComponentEx().getBackground(), 0.6f);
  }

  String tooltip = getStatusText();

  EditorEx patchEditor = myViewer.getPatchEditor();
  Document document = patchEditor.getDocument();
  MarkupModelEx markupModel = patchEditor.getMarkupModel();
  TextRange textRange = DiffUtil.getLinesRange(document, line1, line2);

  RangeHighlighter highlighter = markupModel.addRangeHighlighter(textRange.getStartOffset(), textRange.getEndOffset(),
                                                                 HighlighterLayer.LAST, null, HighlighterTargetArea.LINES_IN_RANGE);

  PairConsumer<Editor, MouseEvent> clickHandler = getResultRange() != null ?
                                                  (e, event) -> myViewer.scrollToChange(this, Side.RIGHT, false) :
                                                  null;
  highlighter.setLineMarkerRenderer(LineStatusMarkerRenderer.createRenderer(line1, line2, color, tooltip, clickHandler));

  myHighlighters.add(highlighter);
}
 
Example #5
Source File: RecentLocationsRenderer.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private static JComponent setupEditorComponent(@Nonnull EditorEx editor, @Nonnull String text, @Nonnull SpeedSearch speedSearch, @Nonnull EditorColorsScheme colorsScheme, boolean selected) {
  Iterable<TextRange> ranges = speedSearch.matchingFragments(text);
  if (ranges != null) {
    selectSearchResultsInEditor(editor, ranges.iterator());
  }
  else {
    RecentLocationsAction.clearSelectionInEditor(editor);
  }

  editor.setBackgroundColor(getBackgroundColor(colorsScheme, selected));
  editor.setBorder(JBUI.Borders.empty(0, 4, 6, 0));

  if (EMPTY_FILE_TEXT.equals(editor.getDocument().getText())) {
    editor.getMarkupModel().addRangeHighlighter(0, EMPTY_FILE_TEXT.length(), HighlighterLayer.SYNTAX, createEmptyTextForegroundTextAttributes(colorsScheme), HighlighterTargetArea.EXACT_RANGE);
  }

  return editor.getComponent();
}
 
Example #6
Source File: AbstractRefactoringPanel.java    From IntelliJDeodorant with MIT License 6 votes vote down vote up
private static void highlightPsiElement(PsiElement psiElement, boolean openInEditor) {
    if (openInEditor) {
        EditorHelper.openInEditor(psiElement);
    }

    Editor editor = FileEditorManager.getInstance(psiElement.getProject()).getSelectedTextEditor();
    if (editor == null) {
        return;
    }

    TextAttributes attributes = EditorColorsManager.getInstance().getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
    editor.getMarkupModel().addRangeHighlighter(
            psiElement.getTextRange().getStartOffset(),
            psiElement.getTextRange().getEndOffset(),
            HighlighterLayer.SELECTION,
            attributes,
            HighlighterTargetArea.EXACT_RANGE
    );
}
 
Example #7
Source File: EditorTextFieldCellRenderer.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected void setTextToEditor(String text) {
  myEditor.getMarkupModel().removeAllHighlighters();
  myEditor.getDocument().setText(text);
  ((DesktopEditorImpl)myEditor).resetSizes();
  myEditor.getHighlighter().setText(text);
  if (myTextAttributes != null) {
    myEditor.getMarkupModel().addRangeHighlighter(0, myEditor.getDocument().getTextLength(), HighlighterLayer.ADDITIONAL_SYNTAX, myTextAttributes, HighlighterTargetArea.EXACT_RANGE);
  }

  ((DesktopEditorImpl)myEditor).setPaintSelection(mySelected);
  SelectionModel selectionModel = myEditor.getSelectionModel();
  selectionModel.setSelection(0, mySelected ? myEditor.getDocument().getTextLength() : 0);
}
 
Example #8
Source File: HighlightUtils.java    From CppTools with Apache License 2.0 5 votes vote down vote up
static RangeHighlighter createRangeMarker(Editor editor, final int rangeOffset, final int rangeOffset2, final int index, TextAttributes attrs) {
  RangeHighlighter rangeHighlighter = editor.getMarkupModel().addRangeHighlighter(
    rangeOffset,
    rangeOffset2,
    index == PP_SKIPPED_INDEX ? HighlighterLayer.LAST:100,
    attrs,
    HighlighterTargetArea.EXACT_RANGE
  );

  if (index == OVERRIDES_INDEX) {
    rangeHighlighter.setGutterIconRenderer(
      new MyGutterIconRenderer(
        IconLoader.getIcon("/gutter/overridingMethod.png"),
        true
      )
    );
  } else if (index == OVERRIDDEN_INDEX) {
    rangeHighlighter.setGutterIconRenderer(
      new MyGutterIconRenderer(
        IconLoader.getIcon("/gutter/overridenMethod.png"),
        false
      )
    );
  }

  return rangeHighlighter;
}
 
Example #9
Source File: DetailViewImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void navigateInPreviewEditor(PreviewEditorState editorState) {
  final VirtualFile file = editorState.getFile();
  final LogicalPosition positionToNavigate = editorState.getNavigate();
  final TextAttributes lineAttributes = editorState.getAttributes();
  Document document = FileDocumentManager.getInstance().getDocument(file);

  clearEditor();
  myEditorState = editorState;
  remove(myLabel);
  if (document != null) {
    if (getEditor() == null || getEditor().getDocument() != document) {
      setEditor(createEditor(myProject, document, file));
      add(getEditor().getComponent(), BorderLayout.CENTER);
    }

    if (positionToNavigate != null) {
      getEditor().getCaretModel().moveToLogicalPosition(positionToNavigate);
      validate();
      getEditor().getScrollingModel().scrollToCaret(ScrollType.CENTER);
    } else {
      revalidate();
      repaint();
    }

    clearHighlighting();
    if (lineAttributes != null && positionToNavigate != null && positionToNavigate.line < getEditor().getDocument().getLineCount()) {
      myHighlighter = getEditor().getMarkupModel().addLineHighlighter(positionToNavigate.line, HighlighterLayer.SELECTION - 1,
                                                                      lineAttributes);
    }
  }
  else {
    myLabel.setText("Navigate to selected " + (file.isDirectory() ? "directory " : "file ") + "in Project View");
    add(myLabel, BorderLayout.CENTER);
    validate();
  }
}
 
Example #10
Source File: LanguageConsoleBuilder.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void addLineSeparatorPainterIfNeed() {
  if (lineSeparatorPainter != null) {
    return;
  }

  RangeHighlighter highlighter = getHistoryViewer().getMarkupModel().addRangeHighlighter(0, getDocument().getTextLength(), HighlighterLayer.ADDITIONAL_SYNTAX, null, HighlighterTargetArea.EXACT_RANGE);
  highlighter.setGreedyToRight(true);
  highlighter.setCustomRenderer(renderer);
  lineSeparatorPainter = highlighter;
}
 
Example #11
Source File: HighlightData.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void addHighlToView(final Editor view, EditorColorsScheme scheme, final Map<TextAttributesKey,String> displayText) {

    // XXX: Hack
    if (HighlighterColors.BAD_CHARACTER.equals(myHighlightType)) {
      return;
    }

    final TextAttributes attr = scheme.getAttributes(myHighlightType);
    if (attr != null) {
      UIUtil.invokeAndWaitIfNeeded((Runnable)() -> {
        try {
          // IDEA-53203: add ERASE_MARKER for manually defined attributes
          view.getMarkupModel().addRangeHighlighter(myStartOffset, myEndOffset, HighlighterLayer.ADDITIONAL_SYNTAX,
                                                    TextAttributes.ERASE_MARKER, HighlighterTargetArea.EXACT_RANGE);
          RangeHighlighter highlighter = view.getMarkupModel()
                  .addRangeHighlighter(myStartOffset, myEndOffset, HighlighterLayer.ADDITIONAL_SYNTAX, attr,
                                       HighlighterTargetArea.EXACT_RANGE);
          final Color errorStripeColor = attr.getErrorStripeColor();
          highlighter.setErrorStripeMarkColor(errorStripeColor);
          final String tooltip = displayText.get(myHighlightType);
          highlighter.setErrorStripeTooltip(tooltip);
        }
        catch (Exception e) {
          throw new RuntimeException(e);
        }
      });
    }
  }
 
Example #12
Source File: TemplateState.java    From consulo with Apache License 2.0 5 votes vote down vote up
private RangeHighlighter getSegmentHighlighter(int segmentNumber, boolean isSelected, boolean isEnd) {
  final TextAttributes lvAttr = EditorColorsManager.getInstance().getGlobalScheme().getAttributes(EditorColors.LIVE_TEMPLATE_ATTRIBUTES);
  TextAttributes attributes = isSelected ? lvAttr : new TextAttributes();
  TextAttributes endAttributes = new TextAttributes();

  int start = mySegments.getSegmentStart(segmentNumber);
  int end = mySegments.getSegmentEnd(segmentNumber);
  RangeHighlighter segmentHighlighter = myEditor.getMarkupModel()
          .addRangeHighlighter(start, end, HighlighterLayer.LAST + 1, isEnd ? endAttributes : attributes, HighlighterTargetArea.EXACT_RANGE);
  segmentHighlighter.setGreedyToLeft(true);
  segmentHighlighter.setGreedyToRight(true);
  return segmentHighlighter;
}
 
Example #13
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 #14
Source File: AbstractValueHint.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void invokeHint(Runnable hideRunnable) {
  myHideRunnable = hideRunnable;

  if (!canShowHint()) {
    hideHint();
    return;
  }

  if (myType == ValueHintType.MOUSE_ALT_OVER_HINT) {
    EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme();
    TextAttributes attributes = scheme.getAttributes(EditorColors.REFERENCE_HYPERLINK_COLOR);
    attributes = NavigationUtil.patchAttributesColor(attributes, myCurrentRange, myEditor);

    myHighlighter = myEditor.getMarkupModel().addRangeHighlighter(myCurrentRange.getStartOffset(), myCurrentRange.getEndOffset(),
                                                                  HighlighterLayer.SELECTION + 1, attributes,
                                                                  HighlighterTargetArea.EXACT_RANGE);
    Component internalComponent = myEditor.getContentComponent();
    myStoredCursor = internalComponent.getCursor();
    internalComponent.addKeyListener(myEditorKeyListener);
    internalComponent.setCursor(hintCursor());
    if (LOG.isDebugEnabled()) {
      LOG.debug("internalComponent.setCursor(hintCursor())");
    }
  }
  else {
    evaluateAndShowHint();
  }
}
 
Example #15
Source File: EditorDocOps.java    From KodeBeagle with Apache License 2.0 5 votes vote down vote up
public final void addHighlighting(final List<Integer> linesForHighlighting,
                                  final Document document) {
    TextAttributes attributes = new TextAttributes();
    JBColor color = JBColor.GREEN;
    attributes.setEffectColor(color);
    attributes.setEffectType(EffectType.SEARCH_MATCH);
    attributes.setBackgroundColor(HIGHLIGHTING_COLOR);
    Editor projectEditor =
            FileEditorManager.getInstance(windowObjects.getProject()).getSelectedTextEditor();
    if (projectEditor != null) {
        PsiFile psiFile =
                PsiDocumentManager.getInstance(windowObjects.getProject()).
                        getPsiFile(projectEditor.getDocument());
        MarkupModel markupModel = projectEditor.getMarkupModel();
        if (markupModel != null) {
            markupModel.removeAllHighlighters();

            for (int line : linesForHighlighting) {
                line = line - 1;
                if (line < document.getLineCount()) {
                    int startOffset = document.getLineStartOffset(line);
                    int endOffset = document.getLineEndOffset(line);
                    String lineText =
                            document.getCharsSequence().
                                    subSequence(startOffset, endOffset).toString();
                    int lineStartOffset =
                            startOffset + lineText.length() - lineText.trim().length();
                    markupModel.addRangeHighlighter(lineStartOffset, endOffset,
                            HighlighterLayer.ERROR, attributes,
                            HighlighterTargetArea.EXACT_RANGE);
                    if (psiFile != null && psiFile.findElementAt(lineStartOffset) != null) {
                        HighlightUsagesHandler.doHighlightElements(projectEditor,
                                new PsiElement[]{psiFile.findElementAt(lineStartOffset)},
                                attributes, false);
                    }
                }
            }
        }
    }
}
 
Example #16
Source File: ExtractMethodPanel.java    From IntelliJDeodorant with MIT License 5 votes vote down vote up
/**
 * Opens definition of method and highlights statements, which should be extracted.
 *
 * @param sourceMethod method from which code is proposed to be extracted into separate method.
 * @param scope        scope of the current project.
 * @param slice        computation slice.
 */
private static void openDefinition(@Nullable PsiMethod sourceMethod, AnalysisScope scope, ASTSlice slice) {
    new Task.Backgroundable(scope.getProject(), "Search Definition") {
        @Override
        public void run(@NotNull ProgressIndicator indicator) {
            indicator.setIndeterminate(true);
        }

        @Override
        public void onSuccess() {
            if (sourceMethod != null) {
                Set<SmartPsiElementPointer<PsiElement>> statements = slice.getSliceStatements();
                PsiStatement psiStatement = (PsiStatement) statements.iterator().next().getElement();
                if (psiStatement != null && psiStatement.isValid()) {
                    EditorHelper.openInEditor(psiStatement);
                    Editor editor = FileEditorManager.getInstance(sourceMethod.getProject()).getSelectedTextEditor();
                    if (editor != null) {
                        TextAttributes attributes = EditorColorsManager.getInstance().getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
                        editor.getMarkupModel().removeAllHighlighters();
                        statements.stream()
                                .filter(statement -> statement.getElement() != null)
                                .forEach(statement ->
                                        editor.getMarkupModel().addRangeHighlighter(statement.getElement().getTextRange().getStartOffset(),
                                                statement.getElement().getTextRange().getEndOffset(), HighlighterLayer.SELECTION,
                                                attributes, HighlighterTargetArea.EXACT_RANGE));
                    }
                }
            }
        }
    }.queue();
}
 
Example #17
Source File: BraceHighlighter.java    From HighlightBracketPair with Apache License 2.0 5 votes vote down vote up
public Pair<RangeHighlighter, RangeHighlighter> highlightPair(BracePair bracePair) {
    final Brace leftBrace = bracePair.getLeftBrace();
    final Brace rightBrace = bracePair.getRightBrace();
    final int leftBraceOffset = leftBrace.getOffset();
    final int rightBraceOffset = rightBrace.getOffset();
    final String leftBraceText = leftBrace.getText();
    final String rightBraceText = rightBrace.getText();

    if (leftBraceOffset == NON_OFFSET ||
            rightBraceOffset == NON_OFFSET)
        return null;
    // try to get the text attr by element type
    TextAttributesKey textAttributesKey =
            HighlightBracketPairSettingsPage.getTextAttributesKeyByToken(leftBrace.getElementType());
    // if not found, get the text attr by brace text
    if (textAttributesKey == null) {
        textAttributesKey = HighlightBracketPairSettingsPage.getTextAttributesKeyByText(leftBraceText);
    }
    final TextAttributes textAttributes = editor.getColorsScheme().getAttributes(textAttributesKey);

    RangeHighlighter leftHighlighter = markupModelEx.addRangeHighlighter(
            leftBraceOffset,
            leftBraceOffset + leftBraceText.length(),
            HighlighterLayer.SELECTION + HIGHLIGHT_LAYER_WEIGHT,
            textAttributes,
            HighlighterTargetArea.EXACT_RANGE);
    RangeHighlighter rightHighlighter = markupModelEx.addRangeHighlighter(
            rightBraceOffset,
            rightBraceOffset + rightBraceText.length(),
            HighlighterLayer.SELECTION + HIGHLIGHT_LAYER_WEIGHT,
            textAttributes,
            HighlighterTargetArea.EXACT_RANGE);
    return new Pair<>(leftHighlighter, rightHighlighter);
}
 
Example #18
Source File: CommentsDiffTool.java    From review-board-idea-plugin with Apache License 2.0 5 votes vote down vote up
private void updateHighLights(Editor editor) {
    MarkupModel markup = editor.getMarkupModel();

    for (RangeHighlighter customRangeHighlighter : newCommentHighlighters) {
        markup.removeHighlighter(customRangeHighlighter);
    }
    newCommentHighlighters.clear();

    int lineCount = markup.getDocument().getLineCount();

    Map<Integer, List<Comment>> lineComments = lineComments(comments);
    for (Map.Entry<Integer, List<Comment>> entry : lineComments.entrySet()) {
        if (entry.getKey() > lineCount) continue;

        boolean hasNewComments = false;
        for (Comment comment : entry.getValue()) {
            if (comment.id == null) {
                hasNewComments = true;
                break;
            }
        }

        TextAttributes attributes = new TextAttributes();
        if (hasNewComments) attributes.setBackgroundColor(JBColor.PINK);
        else attributes.setBackgroundColor(JBColor.YELLOW);

        RangeHighlighter rangeHighlighter = markup
                .addLineHighlighter(entry.getKey() - 1, HighlighterLayer.SELECTION + (hasNewComments ? 2 : 1), attributes);
        rangeHighlighter.setGutterIconRenderer(new CommentGutterIconRenderer());
        newCommentHighlighters.add(rangeHighlighter);
    }
}
 
Example #19
Source File: TextMergeChange.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private MyGutterOperation createOperation(@Nonnull ThreeSide side, @Nonnull OperationType type) {
  if (isResolved(side)) return null;

  EditorEx editor = myViewer.getEditor(side);
  Document document = editor.getDocument();

  int line = getStartLine(side);
  int offset = line == DiffUtil.getLineCount(document) ? document.getTextLength() : document.getLineStartOffset(line);

  RangeHighlighter highlighter =
          editor.getMarkupModel().addRangeHighlighter(offset, offset, HighlighterLayer.ADDITIONAL_SYNTAX, null, HighlighterTargetArea.LINES_IN_RANGE);
  return new MyGutterOperation(side, highlighter, type);
}
 
Example #20
Source File: UnifiedDiffChange.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private MyGutterOperation createOperation(@Nonnull Side sourceSide) {
  int offset = myEditor.getDocument().getLineStartOffset(myLine1);
  RangeHighlighter highlighter = myEditor.getMarkupModel().addRangeHighlighter(offset, offset,
                                                                               HighlighterLayer.ADDITIONAL_SYNTAX,
                                                                               null,
                                                                               HighlighterTargetArea.LINES_IN_RANGE);
  return new MyGutterOperation(sourceSide, highlighter);
}
 
Example #21
Source File: SimpleDiffChange.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private MyGutterOperation createOperation(@Nonnull Side side) {
  int offset = side.getStartOffset(myFragment);
  EditorEx editor = myViewer.getEditor(side);
  RangeHighlighter highlighter = editor.getMarkupModel().addRangeHighlighter(offset, offset,
                                                                             HighlighterLayer.ADDITIONAL_SYNTAX,
                                                                             null,
                                                                             HighlighterTargetArea.LINES_IN_RANGE);
  return new MyGutterOperation(side, highlighter);
}
 
Example #22
Source File: AbstractEditorAnnotation.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Creates a RangeHighlighter with the given position and text attributes for the given editor.
 *
 * <p>The returned <code>RangeHighlighter</code> can not be modified through the API but is
 * automatically updated by Intellij if there are changes to the editor.
 *
 * @param start the start of the highlighted area
 * @param end the end of the highlighted area
 * @param editor the editor to create the highlighter for
 * @param file the file for the editor
 * @return a RangeHighlighter with the given parameters or <code>null</code> if the given end
 *     position is located after the document end
 */
@Nullable
static RangeHighlighter addRangeHighlighter(
    int start,
    int end,
    @NotNull Editor editor,
    @NotNull TextAttributes textAttributes,
    @NotNull IFile file) {

  int documentLength = editor.getDocument().getTextLength();

  if (documentLength < end) {
    log.warn(
        "The creation of a range highlighter with the bounds ("
            + start
            + ", "
            + end
            + ") for the file "
            + file.getReferencePoint().getName()
            + " - "
            + file.getReferencePointRelativePath()
            + " failed as the given end position is located after the "
            + "document end. document length: "
            + documentLength
            + ", end position: "
            + end);

    return null;
  }

  return EDTExecutor.invokeAndWait(
      (Computable<RangeHighlighter>)
          () ->
              editor
                  .getMarkupModel()
                  .addRangeHighlighter(
                      start,
                      end,
                      HighlighterLayer.LAST,
                      textAttributes,
                      HighlighterTargetArea.EXACT_RANGE),
      ModalityState.defaultModalityState());
}
 
Example #23
Source File: CopyCutWithoutSelectAction.java    From emacsIDEAs with Apache License 2.0 4 votes vote down vote up
private RangeHighlighter addHighlighterOnCopiedRange(TextRange tr) {
    TextAttributes textAttributes = new TextAttributes();
    textAttributes.setBackgroundColor(SelectorFactory.HIGHLIGHT_COLOR);
    return _editor.getMarkupModel().addRangeHighlighter(tr.getStartOffset(), tr.getEndOffset(),
            HighlighterLayer.LAST + 1, textAttributes, HighlighterTargetArea.EXACT_RANGE);
}
 
Example #24
Source File: LineMarkersUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
private static RangeHighlighter createOrReuseLineMarker(@Nonnull LineMarkerInfo<?> info, @Nonnull MarkupModelEx markupModel, @Nullable HighlightersRecycler toReuse) {
  LineMarkerInfo.LineMarkerGutterIconRenderer<?> newRenderer = (LineMarkerInfo.LineMarkerGutterIconRenderer<?>)info.createGutterRenderer();

  RangeHighlighter highlighter = toReuse == null ? null : toReuse.pickupHighlighterFromGarbageBin(info.startOffset, info.endOffset, HighlighterLayer.ADDITIONAL_SYNTAX);
  boolean newHighlighter = false;
  if (highlighter == null) {
    newHighlighter = true;
    highlighter = markupModel.addRangeHighlighterAndChangeAttributes(info.startOffset, info.endOffset, HighlighterLayer.ADDITIONAL_SYNTAX, null, HighlighterTargetArea.LINES_IN_RANGE, false, markerEx -> {
              markerEx.setGutterIconRenderer(newRenderer);
              markerEx.setLineSeparatorColor(info.separatorColor);
              markerEx.setLineSeparatorPlacement(info.separatorPlacement);

              markerEx.putUserData(LINE_MARKER_INFO, info);
            });

    MarkupEditorFilter editorFilter = info.getEditorFilter();
    if (editorFilter != MarkupEditorFilter.EMPTY) {
      highlighter.setEditorFilter(editorFilter);
    }
  }

  if (!newHighlighter) {
    highlighter.putUserData(LINE_MARKER_INFO, info);

    LineMarkerInfo.LineMarkerGutterIconRenderer<?> oldRenderer =
            highlighter.getGutterIconRenderer() instanceof LineMarkerInfo.LineMarkerGutterIconRenderer ? (LineMarkerInfo.LineMarkerGutterIconRenderer<?>)highlighter.getGutterIconRenderer() : null;
    boolean rendererChanged = newRenderer == null || !newRenderer.equals(oldRenderer);
    boolean lineSeparatorColorChanged = !Comparing.equal(highlighter.getLineSeparatorColor(), info.separatorColor);
    boolean lineSeparatorPlacementChanged = !Comparing.equal(highlighter.getLineSeparatorPlacement(), info.separatorPlacement);

    if (rendererChanged || lineSeparatorColorChanged || lineSeparatorPlacementChanged) {
      markupModel.changeAttributesInBatch((RangeHighlighterEx)highlighter, markerEx -> {
        if (rendererChanged) {
          markerEx.setGutterIconRenderer(newRenderer);
        }
        if (lineSeparatorColorChanged) {
          markerEx.setLineSeparatorColor(info.separatorColor);
        }
        if (lineSeparatorPlacementChanged) {
          markerEx.setLineSeparatorPlacement(info.separatorPlacement);
        }
      });
    }
  }
  info.highlighter = highlighter;
  return highlighter;
}
 
Example #25
Source File: Filter.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * See {@link HighlighterLayer} for available predefined layers.
 */
public int getHighlighterLayer() {
  return getHyperlinkInfo() != null ? HighlighterLayer.HYPERLINK : HighlighterLayer.CONSOLE_FILTER;
}
 
Example #26
Source File: ConsoleLogConsole.java    From aem-ide-tooling-4-intellij with Apache License 2.0 4 votes vote down vote up
void doPrintNotification(final Notification notification) {
    Editor editor = myLogEditor.getValue();
    if (editor.isDisposed()) {
        return;
    }

    Document document = editor.getDocument();
    boolean scroll = document.getTextLength() == editor.getCaretModel().getOffset() || !editor.getContentComponent().hasFocus();

    Long notificationTime = myProjectModel.getNotificationTime(notification);
    if (notificationTime == null) {
        return;
    }

    String date = DateFormatUtil.formatTimeWithSeconds(notificationTime) + " ";
    append(document, date);

    int startLine = document.getLineCount() - 1;

    ConsoleLog.LogEntry pair = ConsoleLog.formatForLog(notification, StringUtil.repeatSymbol(' ', date.length()));

    final NotificationType type = notification.getType();
    TextAttributesKey key = type == NotificationType.ERROR
        ? ConsoleViewContentType.LOG_ERROR_OUTPUT_KEY
        : type == NotificationType.INFORMATION
        ? ConsoleViewContentType.NORMAL_OUTPUT_KEY
        : ConsoleViewContentType.LOG_WARNING_OUTPUT_KEY;

    int msgStart = document.getTextLength();
    String message = pair.message;
    append(document, message);

    TextAttributes attributes = EditorColorsManager.getInstance().getGlobalScheme().getAttributes(key);
    int layer = HighlighterLayer.CARET_ROW + 1;
    editor.getMarkupModel().addRangeHighlighter(msgStart, document.getTextLength(), layer, attributes, HighlighterTargetArea.EXACT_RANGE);

    for (Pair<TextRange, HyperlinkInfo> link : pair.links) {
        final RangeHighlighter rangeHighlighter = myHyperlinkSupport.getValue()
            .createHyperlink(link.first.getStartOffset() + msgStart, link.first.getEndOffset() + msgStart, null, link.second);
        if (link.second instanceof ConsoleLog.ShowBalloon) {
            ((ConsoleLog.ShowBalloon)link.second).setRangeHighlighter(rangeHighlighter);
        }
    }

    append(document, "\n");

    if (scroll) {
        editor.getCaretModel().moveToOffset(document.getTextLength());
        editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
    }

    if (notification.isImportant()) {
        highlightNotification(notification, pair.status, startLine, document.getLineCount() - 1);
    }
}
 
Example #27
Source File: SyntaxInfoBuilder.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static boolean isInterestedInLayer(int layer) {
  return layer != HighlighterLayer.CARET_ROW && layer != HighlighterLayer.SELECTION && layer != HighlighterLayer.ERROR && layer != HighlighterLayer.WARNING && layer != HighlighterLayer.ELEMENT_UNDER_CARET;
}
 
Example #28
Source File: LSPDiagnosticsToMarkers.java    From intellij-quarkus with Eclipse Public License 2.0 4 votes vote down vote up
private int getLayer(DiagnosticSeverity severity) {
    return severity== DiagnosticSeverity.Error?HighlighterLayer.ERROR:HighlighterLayer.WARNING;
}
 
Example #29
Source File: FindUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nullable
private static FindResult doSearch(@Nonnull Project project,
                                   @Nonnull final Editor editor,
                                   int offset,
                                   boolean toWarn,
                                   @Nonnull FindModel model,
                                   boolean adjustEditor) {
  FindManager findManager = FindManager.getInstance(project);
  Document document = editor.getDocument();

  final FindResult result = findManager.findString(document.getCharsSequence(), offset, model, getVirtualFile(editor));

  boolean isFound = result.isStringFound();
  final SelectionModel selection = editor.getSelectionModel();
  if (isFound && !model.isGlobal()) {
    if (!selectionMayContainRange(selection, result)) {
      isFound = false;
    }
    else if (!selectionStrictlyContainsRange(selection, result)) {
      final int[] starts = selection.getBlockSelectionStarts();
      for (int newOffset : starts) {
        if (newOffset > result.getStartOffset()) {
          return doSearch(project, editor, newOffset, toWarn, model, adjustEditor);
        }
      }
    }
  }
  if (!isFound) {
    if (toWarn) {
      processNotFound(editor, model.getStringToFind(), model, project);
    }
    return null;
  }

  if (adjustEditor) {
    final CaretModel caretModel = editor.getCaretModel();
    final ScrollingModel scrollingModel = editor.getScrollingModel();
    int oldCaretOffset = caretModel.getOffset();
    boolean forward = oldCaretOffset < result.getStartOffset();
    final ScrollType scrollType = forward ? ScrollType.CENTER_DOWN : ScrollType.CENTER_UP;

    if (model.isGlobal()) {
      int targetCaretPosition = result.getEndOffset();
      if (selection.getSelectionEnd() - selection.getSelectionStart() == result.getLength()) {
        // keeping caret's position relative to selection
        // use case: FindNext is used after SelectNextOccurrence action
        targetCaretPosition = caretModel.getOffset() - selection.getSelectionStart() + result.getStartOffset();
      }
      if (caretModel.getCaretAt(editor.offsetToVisualPosition(targetCaretPosition)) != null) {
        // if there's a different caret at target position, don't move current caret/selection
        // use case: FindNext is used after SelectNextOccurrence action
        return result;
      }
      caretModel.moveToOffset(targetCaretPosition);
      selection.removeSelection();
      scrollingModel.scrollToCaret(scrollType);
      scrollingModel.runActionOnScrollingFinished(
              () -> {
                scrollingModel.scrollTo(editor.offsetToLogicalPosition(result.getStartOffset()), scrollType);
                scrollingModel.scrollTo(editor.offsetToLogicalPosition(result.getEndOffset()), scrollType);
              }
      );
    }
    else {
      moveCaretAndDontChangeSelection(editor, result.getStartOffset(), scrollType);
      moveCaretAndDontChangeSelection(editor, result.getEndOffset(), scrollType);
    }
    IdeDocumentHistory.getInstance(project).includeCurrentCommandAsNavigation();

    EditorColorsManager manager = EditorColorsManager.getInstance();
    TextAttributes selectionAttributes = manager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);

    if (!model.isGlobal()) {
      final RangeHighlighterEx segmentHighlighter = (RangeHighlighterEx)editor.getMarkupModel().addRangeHighlighter(
              result.getStartOffset(),
              result.getEndOffset(),
              HighlighterLayer.SELECTION + 1,
              selectionAttributes, HighlighterTargetArea.EXACT_RANGE);
      MyListener listener = new MyListener(editor, segmentHighlighter);
      caretModel.addCaretListener(listener);
    }
    else {
      selection.setSelection(result.getStartOffset(), result.getEndOffset());
    }
  }

  return result;
}
 
Example #30
Source File: EditorHyperlinkSupport.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
public RangeHighlighter createHyperlink(int highlightStartOffset, int highlightEndOffset, @Nullable TextAttributes highlightAttributes, @Nonnull HyperlinkInfo hyperlinkInfo) {
  return createHyperlink(highlightStartOffset, highlightEndOffset, highlightAttributes, hyperlinkInfo, null, HighlighterLayer.HYPERLINK);
}