public static RemoveUnusedVariableUtil.RemoveMode showSideEffectsWarning(
      List<PsiElement> sideEffects,
      PsiVariable variable,
      Editor editor,
      boolean canCopeWithSideEffects,
      @NonNls String beforeText,
      @NonNls String afterText) {
    if (sideEffects.isEmpty()) return RemoveUnusedVariableUtil.RemoveMode.DELETE_ALL;
    if (ApplicationManager.getApplication().isUnitTestMode()) {
      return canCopeWithSideEffects
          ? RemoveUnusedVariableUtil.RemoveMode.MAKE_STATEMENT
          : RemoveUnusedVariableUtil.RemoveMode.DELETE_ALL;
    }
    Project project = editor.getProject();
    HighlightManager highlightManager = HighlightManager.getInstance(project);
    PsiElement[] elements = PsiUtilCore.toPsiElementArray(sideEffects);
    EditorColorsManager manager = EditorColorsManager.getInstance();
    TextAttributes attributes =
        manager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
    highlightManager.addOccurrenceHighlights(editor, elements, attributes, true, null);

    SideEffectWarningDialog dialog =
        new SideEffectWarningDialog(
            project, false, variable, beforeText, afterText, canCopeWithSideEffects);
    dialog.show();
    int code = dialog.getExitCode();
    return RemoveUnusedVariableUtil.RemoveMode.values()[code];
  }
  private void removeFromEditor() {
    Editor editor = mySearchResults.getEditor();
    if (myReplacementBalloon != null) {
      myReplacementBalloon.hide();
    }

    if (editor != null) {

      for (VisibleAreaListener visibleAreaListener : myVisibleAreaListenersToRemove) {
        editor.getScrollingModel().removeVisibleAreaListener(visibleAreaListener);
      }
      myVisibleAreaListenersToRemove.clear();
      Project project = mySearchResults.getProject();
      if (project != null && !project.isDisposed()) {
        for (RangeHighlighter h : myHighlighters) {
          HighlightManager.getInstance(project).removeSegmentHighlighter(editor, h);
        }
        if (myCursorHighlighter != null) {
          HighlightManager.getInstance(project)
              .removeSegmentHighlighter(editor, myCursorHighlighter);
          myCursorHighlighter = null;
        }
      }
      myHighlighters.clear();
      if (myListeningSelection) {
        editor.getSelectionModel().removeSelectionListener(this);
        myListeningSelection = false;
      }
    }
  }
  public void removeComment(
      Editor editor, RangeHighlighter lineHighlighter, RangeHighlighter rangeHighlighter) {
    editor.getMarkupModel().removeHighlighter(lineHighlighter);
    lineHighlighter.dispose();

    if (rangeHighlighter != null) {
      HighlightManager highlightManager = HighlightManager.getInstance(project);
      highlightManager.removeSegmentHighlighter(editor, rangeHighlighter);
    }
  }
 private static void highlightInEditor(
     final Project project, final IncludeDuplicate pair, final Editor editor) {
   final HighlightManager highlightManager = HighlightManager.getInstance(project);
   EditorColorsManager colorsManager = EditorColorsManager.getInstance();
   TextAttributes attributes =
       colorsManager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
   final int startOffset = pair.getStart().getTextRange().getStartOffset();
   final int endOffset = pair.getEnd().getTextRange().getEndOffset();
   highlightManager.addRangeHighlight(editor, startOffset, endOffset, attributes, true, null);
   final LogicalPosition logicalPosition = editor.offsetToLogicalPosition(startOffset);
   editor.getScrollingModel().scrollTo(logicalPosition, ScrollType.MAKE_VISIBLE);
 }
  public static RangeHighlighter highlightRangeComment(
      Comment.Range range, Editor editor, Project project) {
    CharSequence charsSequence = editor.getMarkupModel().getDocument().getCharsSequence();

    RangeUtils.Offset offset = RangeUtils.rangeToTextOffset(charsSequence, range);

    TextAttributes attributes = new TextAttributes();
    attributes.setBackgroundColor(JBColor.YELLOW);
    ArrayList<RangeHighlighter> highlighters = Lists.newArrayList();
    HighlightManager highlightManager = HighlightManager.getInstance(project);
    highlightManager.addRangeHighlight(
        editor, offset.start, offset.end, attributes, false, highlighters);
    return highlighters.get(0);
  }
  private static void highlightElement(@NotNull PsiElement element) {
    final Project project = element.getProject();
    final FileEditorManager editorManager = FileEditorManager.getInstance(project);
    final HighlightManager highlightManager = HighlightManager.getInstance(project);
    final EditorColorsManager editorColorsManager = EditorColorsManager.getInstance();
    final Editor editor = editorManager.getSelectedTextEditor();
    final EditorColorsScheme globalScheme = editorColorsManager.getGlobalScheme();
    final TextAttributes textattributes =
        globalScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
    final PsiElement[] elements = new PsiElement[] {element};
    highlightManager.addOccurrenceHighlights(editor, elements, textattributes, true, null);

    StatusBar.Info.set(
        IntentionPowerPackBundle.message("status.bar.escape.highlighting.message"), project);
  }
  private void updateCursorHighlighting(boolean scroll) {
    hideBalloon();

    if (myCursorHighlighter != null) {
      HighlightManager.getInstance(mySearchResults.getProject())
          .removeSegmentHighlighter(mySearchResults.getEditor(), myCursorHighlighter);
      myCursorHighlighter = null;
    }

    final FindResult cursor = mySearchResults.getCursor();
    Editor editor = mySearchResults.getEditor();
    SelectionModel selection = editor.getSelectionModel();
    if (cursor != null) {
      Set<RangeHighlighter> dummy = new HashSet<RangeHighlighter>();
      highlightRange(
          cursor, new TextAttributes(null, null, Color.BLACK, EffectType.ROUNDED_BOX, 0), dummy);
      if (!dummy.isEmpty()) {
        myCursorHighlighter = dummy.iterator().next();
      }

      if (scroll) {
        if (mySearchResults.getFindModel().isGlobal()) {
          FoldingModel foldingModel = editor.getFoldingModel();
          final FoldRegion[] allRegions = editor.getFoldingModel().getAllFoldRegions();

          foldingModel.runBatchFoldingOperation(
              new Runnable() {
                @Override
                public void run() {
                  for (FoldRegion region : allRegions) {
                    if (!region.isValid()) continue;
                    if (cursor.intersects(TextRange.create(region))) {
                      region.setExpanded(true);
                    }
                  }
                }
              });
          selection.setSelection(cursor.getStartOffset(), cursor.getEndOffset());

          editor.getCaretModel().moveToOffset(cursor.getEndOffset());
          editor.getScrollingModel().scrollToCaret(ScrollType.CENTER);
        } else {
          if (!SearchResults.insideVisibleArea(editor, cursor)) {
            LogicalPosition pos = editor.offsetToLogicalPosition(cursor.getStartOffset());
            editor.getScrollingModel().scrollTo(pos, ScrollType.CENTER);
          }
        }
      }
      editor
          .getScrollingModel()
          .runActionOnScrollingFinished(
              new Runnable() {
                @Override
                public void run() {
                  showReplacementPreview();
                }
              });
    }
  }
  private RangeHighlighter doHightlightRange(
      final TextRange textRange,
      final TextAttributes attributes,
      Set<RangeHighlighter> highlighters) {
    HighlightManager highlightManager = HighlightManager.getInstance(mySearchResults.getProject());

    MarkupModelEx markupModel = (MarkupModelEx) mySearchResults.getEditor().getMarkupModel();

    final RangeHighlighter[] candidate = new RangeHighlighter[1];

    boolean notFound =
        markupModel.processRangeHighlightersOverlappingWith(
            textRange.getStartOffset(),
            textRange.getEndOffset(),
            new Processor<RangeHighlighterEx>() {
              @Override
              public boolean process(RangeHighlighterEx highlighter) {
                TextAttributes textAttributes = highlighter.getTextAttributes();
                if (highlighter.getUserData(SEARCH_MARKER) != null
                    && textAttributes != null
                    && textAttributes.equals(attributes)
                    && highlighter.getStartOffset() == textRange.getStartOffset()
                    && highlighter.getEndOffset() == textRange.getEndOffset()) {
                  candidate[0] = highlighter;
                  return false;
                }
                return true;
              }
            });

    if (!notFound && highlighters.contains(candidate[0])) {
      return candidate[0];
    }
    final ArrayList<RangeHighlighter> dummy = new ArrayList<RangeHighlighter>();
    highlightManager.addRangeHighlight(
        mySearchResults.getEditor(),
        textRange.getStartOffset(),
        textRange.getEndOffset(),
        attributes,
        false,
        dummy);
    final RangeHighlighter h = dummy.get(0);
    highlighters.add(h);
    h.putUserData(SEARCH_MARKER, YES);
    return h;
  }
  @Override
  protected void addHighlights(
      @NotNull Map<TextRange, TextAttributes> ranges,
      @NotNull Editor editor,
      @NotNull Collection<RangeHighlighter> highlighters,
      @NotNull HighlightManager highlightManager) {
    final TextAttributes attributes =
        EditorColorsManager.getInstance()
            .getGlobalScheme()
            .getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
    final V variable = getVariable();
    if (variable != null) {
      final String name = variable.getName();
      LOG.assertTrue(name != null, variable);
      final int variableNameLength = name.length();
      if (isReplaceAllOccurrences()) {
        for (RangeMarker marker : getOccurrenceMarkers()) {
          final int startOffset = marker.getStartOffset();
          highlightManager.addOccurrenceHighlight(
              editor,
              startOffset,
              startOffset + variableNameLength,
              attributes,
              0,
              highlighters,
              null);
        }
      } else if (getExpr() != null) {
        final int startOffset = getExprMarker().getStartOffset();
        highlightManager.addOccurrenceHighlight(
            editor,
            startOffset,
            startOffset + variableNameLength,
            attributes,
            0,
            highlighters,
            null);
      }
    }

    for (RangeHighlighter highlighter : highlighters) {
      highlighter.setGreedyToLeft(true);
      highlighter.setGreedyToRight(true);
    }
  }
  public void actionPerformed(AnActionEvent e) {
    DataContext dataContext = e.getDataContext();
    Editor editor = PlatformDataKeys.EDITOR.getData(dataContext);
    Project project = PlatformDataKeys.PROJECT.getData(dataContext);
    PsiElement element = getElementToCopy(editor, dataContext);

    if (!doCopy(element, project, editor) && editor != null) {
      Document document = editor.getDocument();
      PsiFile file = PsiDocumentManager.getInstance(project).getCachedPsiFile(document);
      if (file != null) {
        String toCopy =
            getFileFqn(file) + ":" + (editor.getCaretModel().getLogicalPosition().line + 1);
        CopyPasteManager.getInstance().setContents(new StringSelection(toCopy));
        setStatusBarText(project, toCopy + " has been copied");
      }
      return;
    }

    HighlightManager highlightManager = HighlightManager.getInstance(project);
    EditorColorsManager manager = EditorColorsManager.getInstance();
    TextAttributes attributes =
        manager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
    if (element != null && editor != null) {
      PsiElement nameIdentifier = HighlightUsagesHandler.getNameIdentifier(element);
      if (nameIdentifier != null) {
        highlightManager.addOccurrenceHighlights(
            editor, new PsiElement[] {nameIdentifier}, attributes, true, null);
      } else {
        PsiReference reference =
            TargetElementUtilBase.findReference(editor, editor.getCaretModel().getOffset());
        if (reference != null) {
          highlightManager.addOccurrenceHighlights(
              editor, new PsiReference[] {reference}, attributes, true, null);
        } else {
          highlightManager.addOccurrenceHighlights(
              editor, new PsiElement[] {element}, attributes, true, null);
        }
      }
    }
  }
  private static void highlightWord(
      final Editor editor,
      final CompletionVariant variant,
      final Project project,
      CompletionData data) {
    int delta =
        data.startOffset < variant.offset
            ? variant.variant.length() - data.myWordUnderCursor.length()
            : 0;

    HighlightManager highlightManager = HighlightManager.getInstance(project);
    EditorColorsManager colorManager = EditorColorsManager.getInstance();
    TextAttributes attributes =
        colorManager.getGlobalScheme().getAttributes(EditorColors.TEXT_SEARCH_RESULT_ATTRIBUTES);
    highlightManager.addOccurrenceHighlight(
        editor,
        variant.offset + delta,
        variant.offset + variant.variant.length() + delta,
        attributes,
        HighlightManager.HIDE_BY_ANY_KEY,
        null,
        null);
  }
  private void updateInSelectionHighlighters() {
    if (mySearchResults.getEditor() == null) return;
    final SelectionModel selectionModel = mySearchResults.getEditor().getSelectionModel();
    int[] starts = selectionModel.getBlockSelectionStarts();
    int[] ends = selectionModel.getBlockSelectionEnds();

    final HashSet<RangeHighlighter> toRemove = new HashSet<RangeHighlighter>();
    Set<RangeHighlighter> toAdd = new HashSet<RangeHighlighter>();
    for (RangeHighlighter highlighter : myHighlighters) {
      boolean intersectsWithSelection = false;
      for (int i = 0; i < starts.length; ++i) {
        TextRange selectionRange = new TextRange(starts[i], ends[i]);
        intersectsWithSelection =
            selectionRange.intersects(highlighter.getStartOffset(), highlighter.getEndOffset())
                && selectionRange.getEndOffset() != highlighter.getStartOffset()
                && highlighter.getEndOffset() != selectionRange.getStartOffset();
        if (intersectsWithSelection) break;
      }

      final Object userData = highlighter.getUserData(IN_SELECTION_KEY);
      if (userData != null) {
        if (!intersectsWithSelection) {
          if (userData == IN_SELECTION2) {
            HighlightManager.getInstance(mySearchResults.getProject())
                .removeSegmentHighlighter(mySearchResults.getEditor(), highlighter);
            toRemove.add(highlighter);
          } else {
            highlighter.putUserData(IN_SELECTION_KEY, null);
          }
        }
      } else if (intersectsWithSelection) {
        TextRange cursor = mySearchResults.getCursor();
        if (cursor != null
            && highlighter.getStartOffset() == cursor.getStartOffset()
            && highlighter.getEndOffset() == cursor.getEndOffset()) continue;
        final RangeHighlighter toAnnotate =
            highlightRange(
                new TextRange(highlighter.getStartOffset(), highlighter.getEndOffset()),
                new TextAttributes(null, null, Color.WHITE, EffectType.ROUNDED_BOX, 0),
                toAdd);
        highlighter.putUserData(IN_SELECTION_KEY, IN_SELECTION1);
        toAnnotate.putUserData(IN_SELECTION_KEY, IN_SELECTION2);
      }
    }
    myHighlighters.removeAll(toRemove);
    myHighlighters.addAll(toAdd);
  }
 private static void highlightError(Project project, Editor editor, PsiElement errorElement) {
   if (editor != null) {
     final TextAttributes attributes =
         EditorColorsManager.getInstance()
             .getGlobalScheme()
             .getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
     final TextRange textRange = errorElement.getTextRange();
     HighlightManager.getInstance(project)
         .addRangeHighlight(
             editor,
             textRange.getStartOffset(),
             textRange.getEndOffset(),
             attributes,
             true,
             new ArrayList<>());
   }
 }
 private void clearUnusedHightlighters() {
   Set<RangeHighlighter> unused = new com.intellij.util.containers.HashSet<RangeHighlighter>();
   for (RangeHighlighter highlighter : myHighlighters) {
     if (highlighter.getUserData(MARKER_USED) == null) {
       unused.add(highlighter);
     } else {
       highlighter.putUserData(MARKER_USED, null);
     }
   }
   myHighlighters.removeAll(unused);
   Project project = mySearchResults.getProject();
   if (!project.isDisposed()) {
     for (RangeHighlighter highlighter : unused) {
       HighlightManager.getInstance(project)
           .removeSegmentHighlighter(mySearchResults.getEditor(), highlighter);
     }
   }
 }
  @Override
  @NotNull
  public AnnotationPlace chooseAnnotationsPlace(@NotNull final PsiElement element) {
    if (!element.isPhysical()) return AnnotationPlace.IN_CODE; // element just created
    if (!element.getManager().isInProject(element)) return AnnotationPlace.EXTERNAL;
    final Project project = myPsiManager.getProject();
    final PsiFile containingFile = element.getContainingFile();
    final VirtualFile virtualFile = containingFile.getVirtualFile();
    LOG.assertTrue(virtualFile != null);
    final List<OrderEntry> entries =
        ProjectRootManager.getInstance(project).getFileIndex().getOrderEntriesForFile(virtualFile);
    if (!entries.isEmpty()) {
      for (OrderEntry entry : entries) {
        if (!(entry instanceof ModuleOrderEntry)) {
          if (AnnotationOrderRootType.getUrls(entry).length > 0) {
            return AnnotationPlace.EXTERNAL;
          }
          break;
        }
      }
    }
    final MyExternalPromptDialog dialog =
        ApplicationManager.getApplication().isUnitTestMode()
                || ApplicationManager.getApplication().isHeadlessEnvironment()
            ? null
            : new MyExternalPromptDialog(project);
    if (dialog != null && dialog.isToBeShown()) {
      final PsiElement highlightElement =
          element instanceof PsiNameIdentifierOwner
              ? ((PsiNameIdentifierOwner) element).getNameIdentifier()
              : element.getNavigationElement();
      LOG.assertTrue(highlightElement != null);
      final Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
      final List<RangeHighlighter> highlighters = new ArrayList<RangeHighlighter>();
      final boolean highlight =
          editor != null
              && editor.getDocument()
                  == PsiDocumentManager.getInstance(project).getDocument(containingFile);
      try {
        if (highlight) { // do not highlight for batch inspections
          final EditorColorsManager colorsManager = EditorColorsManager.getInstance();
          final TextAttributes attributes =
              colorsManager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
          final TextRange textRange = highlightElement.getTextRange();
          HighlightManager.getInstance(project)
              .addRangeHighlight(
                  editor,
                  textRange.getStartOffset(),
                  textRange.getEndOffset(),
                  attributes,
                  true,
                  highlighters);
          final LogicalPosition logicalPosition =
              editor.offsetToLogicalPosition(textRange.getStartOffset());
          editor.getScrollingModel().scrollTo(logicalPosition, ScrollType.CENTER);
        }

        dialog.show();
        if (dialog.getExitCode() == 2) {
          return AnnotationPlace.EXTERNAL;
        } else if (dialog.getExitCode() == 1) {
          return AnnotationPlace.NOWHERE;
        }

      } finally {
        if (highlight) {
          HighlightManager.getInstance(project)
              .removeSegmentHighlighter(editor, highlighters.get(0));
        }
      }
    } else if (dialog != null) {
      dialog.close(DialogWrapper.OK_EXIT_CODE);
    }
    return AnnotationPlace.IN_CODE;
  }