use of com.intellij.openapi.editor.ex.RangeHighlighterEx in project intellij-community by JetBrains.
the class ProcessWithConsoleRunner method getHighlightedStringsInConsole.
/**
* Gets highlighted information from test console. Some parts of output (like file links) may be highlighted, and you need to check them.
*
* @return pair of [[ranges], [texts]] where range is [from,to] in doc. for each region, and "text" is text extracted from this region.
* For example assume that in document "spam eggs ham" words "ham" and "spam" are highlighted.
* You should have 2 ranges (0, 4) and (10, 13) and 2 strings (spam and ham)
*/
@NotNull
public Pair<List<Pair<Integer, Integer>>, List<String>> getHighlightedStringsInConsole() {
final List<String> resultStrings = new ArrayList<>();
final List<Pair<Integer, Integer>> resultRanges = new ArrayList<>();
ApplicationManager.getApplication().invokeAndWait(() -> {
myConsole.flushDeferredText();
final Editor editor = myConsole.getEditor();
for (final RangeHighlighter highlighter : editor.getMarkupModel().getAllHighlighters()) {
if (highlighter instanceof RangeHighlighterEx) {
final int start = ((RangeHighlighterEx) highlighter).getAffectedAreaStartOffset();
final int end = ((RangeHighlighterEx) highlighter).getAffectedAreaEndOffset();
resultRanges.add(Pair.create(start, end));
resultStrings.add(editor.getDocument().getText().substring(start, end));
}
}
}, ModalityState.NON_MODAL);
return Pair.create(resultRanges, resultStrings);
}
use of com.intellij.openapi.editor.ex.RangeHighlighterEx in project intellij-community by JetBrains.
the class DaemonCodeAnalyzerImpl method isOffsetInsideHighlightInfo.
private static boolean isOffsetInsideHighlightInfo(int offset, @NotNull HighlightInfo info, boolean includeFixRange) {
RangeHighlighterEx highlighter = info.getHighlighter();
if (highlighter == null || !highlighter.isValid())
return false;
int startOffset = highlighter.getStartOffset();
int endOffset = highlighter.getEndOffset();
if (startOffset <= offset && offset <= endOffset) {
return true;
}
if (!includeFixRange)
return false;
RangeMarker fixMarker = info.fixMarker;
if (fixMarker != null) {
// null means its range is the same as highlighter
if (!fixMarker.isValid())
return false;
startOffset = fixMarker.getStartOffset();
endOffset = fixMarker.getEndOffset();
return startOffset <= offset && offset <= endOffset;
}
return false;
}
use of com.intellij.openapi.editor.ex.RangeHighlighterEx in project intellij-community by JetBrains.
the class FindUtil method doSearch.
@Nullable
private static FindResult doSearch(@NotNull Project project, @NotNull final Editor editor, int offset, boolean toWarn, @NotNull 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) {
// 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;
}
use of com.intellij.openapi.editor.ex.RangeHighlighterEx in project intellij-community by JetBrains.
the class JumpToColorsAndFontsAction method actionPerformed.
@Override
public void actionPerformed(AnActionEvent e) {
// todo handle ColorKey's as well
Project project = e.getData(CommonDataKeys.PROJECT);
Editor editor = e.getData(CommonDataKeys.EDITOR);
if (project == null || editor == null)
return;
Map<TextAttributesKey, Pair<ColorSettingsPage, AttributesDescriptor>> keyMap = ContainerUtil.newHashMap();
Processor<RangeHighlighterEx> processor = r -> {
Object tt = r.getErrorStripeTooltip();
TextAttributesKey key = tt instanceof HighlightInfo ? ObjectUtils.chooseNotNull(((HighlightInfo) tt).forcedTextAttributesKey, ((HighlightInfo) tt).type.getAttributesKey()) : null;
Pair<ColorSettingsPage, AttributesDescriptor> p = key == null ? null : ColorSettingsPages.getInstance().getAttributeDescriptor(key);
if (p != null)
keyMap.put(key, p);
return true;
};
JBIterable<Editor> editors = editor instanceof EditorWindow ? JBIterable.of(editor, ((EditorWindow) editor).getDelegate()) : JBIterable.of(editor);
for (Editor ed : editors) {
TextRange selection = EditorUtil.getSelectionInAnyMode(ed);
MarkupModel forDocument = DocumentMarkupModel.forDocument(ed.getDocument(), project, false);
if (forDocument != null) {
((MarkupModelEx) forDocument).processRangeHighlightersOverlappingWith(selection.getStartOffset(), selection.getEndOffset(), processor);
}
((MarkupModelEx) ed.getMarkupModel()).processRangeHighlightersOverlappingWith(selection.getStartOffset(), selection.getEndOffset(), processor);
EditorHighlighter highlighter = ed instanceof EditorEx ? ((EditorEx) ed).getHighlighter() : null;
SyntaxHighlighter syntaxHighlighter = highlighter instanceof LexerEditorHighlighter ? ((LexerEditorHighlighter) highlighter).getSyntaxHighlighter() : null;
if (syntaxHighlighter != null) {
HighlighterIterator iterator = highlighter.createIterator(selection.getStartOffset());
while (!iterator.atEnd()) {
for (TextAttributesKey key : syntaxHighlighter.getTokenHighlights(iterator.getTokenType())) {
Pair<ColorSettingsPage, AttributesDescriptor> p = key == null ? null : ColorSettingsPages.getInstance().getAttributeDescriptor(key);
if (p != null)
keyMap.put(key, p);
}
if (iterator.getEnd() >= selection.getEndOffset())
break;
iterator.advance();
}
}
}
if (keyMap.isEmpty()) {
HintManager.getInstance().showErrorHint(editor, "No text attributes found");
} else if (keyMap.size() == 1) {
Pair<ColorSettingsPage, AttributesDescriptor> p = keyMap.values().iterator().next();
if (!openSettingsAndSelectKey(project, p.first, p.second)) {
HintManager.getInstance().showErrorHint(editor, "No appropriate settings page found");
}
} else {
ArrayList<Pair<ColorSettingsPage, AttributesDescriptor>> attrs = ContainerUtil.newArrayList(keyMap.values());
Collections.sort(attrs, (o1, o2) -> StringUtil.naturalCompare(o1.first.getDisplayName() + o1.second.getDisplayName(), o2.first.getDisplayName() + o2.second.getDisplayName()));
EditorColorsScheme colorsScheme = editor.getColorsScheme();
JBList<Pair<ColorSettingsPage, AttributesDescriptor>> list = new JBList<>(attrs);
list.setCellRenderer(new ColoredListCellRenderer<Pair<ColorSettingsPage, AttributesDescriptor>>() {
@Override
protected void customizeCellRenderer(@NotNull JList<? extends Pair<ColorSettingsPage, AttributesDescriptor>> list, Pair<ColorSettingsPage, AttributesDescriptor> value, int index, boolean selected, boolean hasFocus) {
TextAttributes ta = colorsScheme.getAttributes(value.second.getKey());
Color fg = ObjectUtils.chooseNotNull(ta.getForegroundColor(), colorsScheme.getDefaultForeground());
Color bg = ObjectUtils.chooseNotNull(ta.getBackgroundColor(), colorsScheme.getDefaultBackground());
SimpleTextAttributes sa = fromTextAttributes(ta);
SimpleTextAttributes saOpaque = sa.derive(STYLE_OPAQUE | sa.getStyle(), fg, bg, null);
SimpleTextAttributes saSelected = REGULAR_ATTRIBUTES.derive(sa.getStyle(), null, null, null);
SimpleTextAttributes saCur = REGULAR_ATTRIBUTES;
List<String> split = StringUtil.split(value.first.getDisplayName() + "//" + value.second.getDisplayName(), "//");
for (int i = 0, len = split.size(); i < len; i++) {
boolean last = i == len - 1;
saCur = !last ? REGULAR_ATTRIBUTES : selected ? saSelected : saOpaque;
if (last)
append(" ", saCur);
append(split.get(i), saCur);
if (last)
append(" ", saCur);
else
append(" > ", GRAYED_ATTRIBUTES);
}
Color stripeColor = ta.getErrorStripeColor();
boolean addStripe = stripeColor != null && stripeColor != saCur.getBgColor();
boolean addBoxed = ta.getEffectType() == EffectType.BOXED && ta.getEffectColor() != null;
if (addBoxed) {
append("▢" + (addStripe ? "" : " "), saCur.derive(-1, ta.getEffectColor(), null, null));
}
if (addStripe) {
append(" ", saCur.derive(STYLE_OPAQUE, null, stripeColor, null));
}
}
});
JBPopupFactory.getInstance().createListPopupBuilder(list).setTitle(StringUtil.notNullize(e.getPresentation().getText())).setMovable(false).setResizable(false).setRequestFocus(true).setItemChoosenCallback(() -> {
Pair<ColorSettingsPage, AttributesDescriptor> p = list.getSelectedValue();
if (p != null && !openSettingsAndSelectKey(project, p.first, p.second)) {
HintManager.getInstance().showErrorHint(editor, "No appropriate settings page found");
}
}).createPopup().showInBestPositionFor(editor);
}
}
use of com.intellij.openapi.editor.ex.RangeHighlighterEx in project intellij-community by JetBrains.
the class ShowIntentionsPass method getActionsToShow.
public static void getActionsToShow(@NotNull final Editor hostEditor, @NotNull final PsiFile hostFile, @NotNull final IntentionsInfo intentions, int passIdToShowIntentionsFor) {
final PsiElement psiElement = hostFile.findElementAt(hostEditor.getCaretModel().getOffset());
LOG.assertTrue(psiElement == null || psiElement.isValid(), psiElement);
int offset = hostEditor.getCaretModel().getOffset();
final Project project = hostFile.getProject();
List<HighlightInfo.IntentionActionDescriptor> fixes = getAvailableFixes(hostEditor, hostFile, passIdToShowIntentionsFor);
final DaemonCodeAnalyzer codeAnalyzer = DaemonCodeAnalyzer.getInstance(project);
final Document hostDocument = hostEditor.getDocument();
HighlightInfo infoAtCursor = ((DaemonCodeAnalyzerImpl) codeAnalyzer).findHighlightByOffset(hostDocument, offset, true);
if (infoAtCursor == null) {
intentions.errorFixesToShow.addAll(fixes);
} else {
final boolean isError = infoAtCursor.getSeverity() == HighlightSeverity.ERROR;
for (HighlightInfo.IntentionActionDescriptor fix : fixes) {
if (fix.isError() && isError) {
intentions.errorFixesToShow.add(fix);
} else {
intentions.inspectionFixesToShow.add(fix);
}
}
}
for (final IntentionAction action : IntentionManager.getInstance().getAvailableIntentionActions()) {
Pair<PsiFile, Editor> place = ShowIntentionActionsHandler.chooseBetweenHostAndInjected(hostFile, hostEditor, (psiFile, editor) -> ShowIntentionActionsHandler.availableFor(psiFile, editor, action));
if (place != null) {
List<IntentionAction> enableDisableIntentionAction = new ArrayList<>();
enableDisableIntentionAction.add(new IntentionHintComponent.EnableDisableIntentionAction(action));
enableDisableIntentionAction.add(new IntentionHintComponent.EditIntentionSettingsAction(action));
HighlightInfo.IntentionActionDescriptor descriptor = new HighlightInfo.IntentionActionDescriptor(action, enableDisableIntentionAction, null);
if (!fixes.contains(descriptor)) {
intentions.intentionsToShow.add(descriptor);
}
}
}
if (HighlightingLevelManager.getInstance(project).shouldInspect(hostFile)) {
PsiElement intentionElement = psiElement;
int intentionOffset = offset;
if (psiElement instanceof PsiWhiteSpace && offset == psiElement.getTextRange().getStartOffset() && offset > 0) {
final PsiElement prev = hostFile.findElementAt(offset - 1);
if (prev != null && prev.isValid()) {
intentionElement = prev;
intentionOffset = offset - 1;
}
}
if (intentionElement != null && intentionElement.getManager().isInProject(intentionElement)) {
collectIntentionsFromDoNotShowLeveledInspections(project, hostFile, intentionElement, intentionOffset, intentions);
}
}
final int line = hostDocument.getLineNumber(offset);
MarkupModelEx model = (MarkupModelEx) DocumentMarkupModel.forDocument(hostDocument, project, true);
List<RangeHighlighterEx> result = new ArrayList<>();
Processor<RangeHighlighterEx> processor = Processors.cancelableCollectProcessor(result);
model.processRangeHighlightersOverlappingWith(hostDocument.getLineStartOffset(line), hostDocument.getLineEndOffset(line), processor);
GutterIntentionAction.addActions(hostEditor, intentions, project, result);
boolean cleanup = appendCleanupCode(intentions.inspectionFixesToShow, hostFile);
if (!cleanup) {
appendCleanupCode(intentions.errorFixesToShow, hostFile);
}
EditorNotificationActions.collectDescriptorsForEditor(hostEditor, intentions.notificationActionsToShow);
intentions.filterActions(hostFile);
}
Aggregations