Search in sources :

Example 26 with HighlighterIterator

use of com.intellij.openapi.editor.highlighter.HighlighterIterator 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);
    }
}
Also used : Settings(com.intellij.openapi.options.ex.Settings) JBIterable(com.intellij.util.containers.JBIterable) HighlightInfo(com.intellij.codeInsight.daemon.impl.HighlightInfo) EditorUtil(com.intellij.openapi.editor.ex.util.EditorUtil) MarkupModelEx(com.intellij.openapi.editor.ex.MarkupModelEx) DocumentMarkupModel(com.intellij.openapi.editor.impl.DocumentMarkupModel) ContainerUtil(com.intellij.util.containers.ContainerUtil) ColorSettingsPage(com.intellij.openapi.options.colors.ColorSettingsPage) ArrayList(java.util.ArrayList) SyntaxHighlighter(com.intellij.openapi.fileTypes.SyntaxHighlighter) ShowSettingsUtilImpl(com.intellij.ide.actions.ShowSettingsUtilImpl) RangeHighlighterEx(com.intellij.openapi.editor.ex.RangeHighlighterEx) HighlighterIterator(com.intellij.openapi.editor.highlighter.HighlighterIterator) Map(java.util.Map) EffectType(com.intellij.openapi.editor.markup.EffectType) Project(com.intellij.openapi.project.Project) EditorEx(com.intellij.openapi.editor.ex.EditorEx) CommonDataKeys(com.intellij.openapi.actionSystem.CommonDataKeys) LexerEditorHighlighter(com.intellij.openapi.editor.ex.util.LexerEditorHighlighter) SimpleTextAttributes(com.intellij.ui.SimpleTextAttributes) JBList(com.intellij.ui.components.JBList) ColorSettingsPages(com.intellij.openapi.options.colors.ColorSettingsPages) EditorHighlighter(com.intellij.openapi.editor.highlighter.EditorHighlighter) StringUtil(com.intellij.openapi.util.text.StringUtil) ActionCallback(com.intellij.openapi.util.ActionCallback) EditorColorsScheme(com.intellij.openapi.editor.colors.EditorColorsScheme) AttributesDescriptor(com.intellij.openapi.options.colors.AttributesDescriptor) SettingsDialog(com.intellij.openapi.options.newEditor.SettingsDialog) TextRange(com.intellij.openapi.util.TextRange) Editor(com.intellij.openapi.editor.Editor) EditorWindow(com.intellij.injected.editor.EditorWindow) MarkupModel(com.intellij.openapi.editor.markup.MarkupModel) java.awt(java.awt) TextAttributesKey(com.intellij.openapi.editor.colors.TextAttributesKey) DumbAwareAction(com.intellij.openapi.project.DumbAwareAction) List(java.util.List) TextAttributes(com.intellij.openapi.editor.markup.TextAttributes) JBPopupFactory(com.intellij.openapi.ui.popup.JBPopupFactory) ColoredListCellRenderer(com.intellij.ui.ColoredListCellRenderer) Processor(com.intellij.util.Processor) AnActionEvent(com.intellij.openapi.actionSystem.AnActionEvent) Pair(com.intellij.openapi.util.Pair) ObjectUtils(com.intellij.util.ObjectUtils) HintManager(com.intellij.codeInsight.hint.HintManager) NotNull(org.jetbrains.annotations.NotNull) Collections(java.util.Collections) SearchableConfigurable(com.intellij.openapi.options.SearchableConfigurable) javax.swing(javax.swing) EditorEx(com.intellij.openapi.editor.ex.EditorEx) HighlightInfo(com.intellij.codeInsight.daemon.impl.HighlightInfo) ArrayList(java.util.ArrayList) TextAttributesKey(com.intellij.openapi.editor.colors.TextAttributesKey) SyntaxHighlighter(com.intellij.openapi.fileTypes.SyntaxHighlighter) LexerEditorHighlighter(com.intellij.openapi.editor.ex.util.LexerEditorHighlighter) NotNull(org.jetbrains.annotations.NotNull) RangeHighlighterEx(com.intellij.openapi.editor.ex.RangeHighlighterEx) SimpleTextAttributes(com.intellij.ui.SimpleTextAttributes) SimpleTextAttributes(com.intellij.ui.SimpleTextAttributes) TextAttributes(com.intellij.openapi.editor.markup.TextAttributes) EditorColorsScheme(com.intellij.openapi.editor.colors.EditorColorsScheme) ColorSettingsPage(com.intellij.openapi.options.colors.ColorSettingsPage) Pair(com.intellij.openapi.util.Pair) LexerEditorHighlighter(com.intellij.openapi.editor.ex.util.LexerEditorHighlighter) EditorHighlighter(com.intellij.openapi.editor.highlighter.EditorHighlighter) AttributesDescriptor(com.intellij.openapi.options.colors.AttributesDescriptor) TextRange(com.intellij.openapi.util.TextRange) ColoredListCellRenderer(com.intellij.ui.ColoredListCellRenderer) EditorWindow(com.intellij.injected.editor.EditorWindow) Project(com.intellij.openapi.project.Project) MarkupModelEx(com.intellij.openapi.editor.ex.MarkupModelEx) JBList(com.intellij.ui.components.JBList) Editor(com.intellij.openapi.editor.Editor) DocumentMarkupModel(com.intellij.openapi.editor.impl.DocumentMarkupModel) MarkupModel(com.intellij.openapi.editor.markup.MarkupModel) HighlighterIterator(com.intellij.openapi.editor.highlighter.HighlighterIterator)

Example 27 with HighlighterIterator

use of com.intellij.openapi.editor.highlighter.HighlighterIterator in project intellij-community by JetBrains.

the class TypedHandler method handleAfterLParen.

private static void handleAfterLParen(@NotNull Editor editor, @NotNull FileType fileType, char lparenChar) {
    int offset = editor.getCaretModel().getOffset();
    HighlighterIterator iterator = ((EditorEx) editor).getHighlighter().createIterator(offset);
    boolean atEndOfDocument = offset == editor.getDocument().getTextLength();
    if (!atEndOfDocument)
        iterator.retreat();
    if (iterator.atEnd())
        return;
    BraceMatcher braceMatcher = BraceMatchingUtil.getBraceMatcher(fileType, iterator);
    if (iterator.atEnd())
        return;
    IElementType braceTokenType = iterator.getTokenType();
    final CharSequence fileText = editor.getDocument().getCharsSequence();
    if (!braceMatcher.isLBraceToken(iterator, fileText, fileType))
        return;
    if (!iterator.atEnd()) {
        iterator.advance();
        if (!iterator.atEnd() && !BraceMatchingUtil.isPairedBracesAllowedBeforeTypeInFileType(braceTokenType, iterator.getTokenType(), fileType)) {
            return;
        }
        iterator.retreat();
    }
    int lparenOffset = BraceMatchingUtil.findLeftmostLParen(iterator, braceTokenType, fileText, fileType);
    if (lparenOffset < 0)
        lparenOffset = 0;
    iterator = ((EditorEx) editor).getHighlighter().createIterator(lparenOffset);
    boolean matched = BraceMatchingUtil.matchBrace(fileText, fileType, iterator, true, true);
    if (!matched) {
        String text;
        if (lparenChar == '(') {
            text = ")";
        } else if (lparenChar == '[') {
            text = "]";
        } else if (lparenChar == '<') {
            text = ">";
        } else if (lparenChar == '{') {
            text = "}";
        } else {
            throw new AssertionError("Unknown char " + lparenChar);
        }
        editor.getDocument().insertString(offset, text);
    }
}
Also used : IElementType(com.intellij.psi.tree.IElementType) NontrivialBraceMatcher(com.intellij.codeInsight.highlighting.NontrivialBraceMatcher) BraceMatcher(com.intellij.codeInsight.highlighting.BraceMatcher) EditorEx(com.intellij.openapi.editor.ex.EditorEx) HighlighterIterator(com.intellij.openapi.editor.highlighter.HighlighterIterator)

Example 28 with HighlighterIterator

use of com.intellij.openapi.editor.highlighter.HighlighterIterator in project intellij-community by JetBrains.

the class TypedHandler method handleQuote.

private static boolean handleQuote(@NotNull Editor editor, char quote, @NotNull PsiFile file) {
    if (!CodeInsightSettings.getInstance().AUTOINSERT_PAIR_QUOTE)
        return false;
    final QuoteHandler quoteHandler = getQuoteHandler(file, editor);
    if (quoteHandler == null)
        return false;
    int offset = editor.getCaretModel().getOffset();
    final Document document = editor.getDocument();
    CharSequence chars = document.getCharsSequence();
    int length = document.getTextLength();
    if (isTypingEscapeQuote(editor, quoteHandler, offset))
        return false;
    if (offset < length && chars.charAt(offset) == quote) {
        if (isClosingQuote(editor, quoteHandler, offset)) {
            EditorModificationUtil.moveCaretRelatively(editor, 1);
            return true;
        }
    }
    HighlighterIterator iterator = ((EditorEx) editor).getHighlighter().createIterator(offset);
    if (!iterator.atEnd()) {
        IElementType tokenType = iterator.getTokenType();
        if (quoteHandler instanceof JavaLikeQuoteHandler) {
            try {
                if (!((JavaLikeQuoteHandler) quoteHandler).isAppropriateElementTypeForLiteral(tokenType))
                    return false;
            } catch (AbstractMethodError incompatiblePluginErrorThatDoesNotInterestUs) {
            // ignore
            }
        }
    }
    type(editor, quote);
    offset = editor.getCaretModel().getOffset();
    if (quoteHandler instanceof MultiCharQuoteHandler) {
        CharSequence closingQuote = getClosingQuote(editor, (MultiCharQuoteHandler) quoteHandler, offset);
        if (closingQuote != null && hasNonClosedLiterals(editor, quoteHandler, offset - 1)) {
            if (offset == document.getTextLength() || !Character.isUnicodeIdentifierPart(document.getCharsSequence().charAt(offset))) {
                //any better heuristic or an API?
                document.insertString(offset, closingQuote);
                return true;
            }
        }
    }
    if (isOpeningQuote(editor, quoteHandler, offset - 1) && hasNonClosedLiterals(editor, quoteHandler, offset - 1)) {
        if (offset == document.getTextLength() || !Character.isUnicodeIdentifierPart(document.getCharsSequence().charAt(offset))) {
            //any better heuristic or an API?
            document.insertString(offset, String.valueOf(quote));
        }
    }
    return true;
}
Also used : IElementType(com.intellij.psi.tree.IElementType) HighlighterIterator(com.intellij.openapi.editor.highlighter.HighlighterIterator)

Example 29 with HighlighterIterator

use of com.intellij.openapi.editor.highlighter.HighlighterIterator in project intellij-community by JetBrains.

the class TypedHandler method indentBrace.

private static void indentBrace(@NotNull final Project project, @NotNull final Editor editor, final char braceChar) {
    final int offset = editor.getCaretModel().getOffset() - 1;
    final Document document = editor.getDocument();
    CharSequence chars = document.getCharsSequence();
    if (offset < 0 || chars.charAt(offset) != braceChar)
        return;
    int spaceStart = CharArrayUtil.shiftBackward(chars, offset - 1, " \t");
    if (spaceStart < 0 || chars.charAt(spaceStart) == '\n' || chars.charAt(spaceStart) == '\r') {
        PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
        documentManager.commitDocument(document);
        final PsiFile file = documentManager.getPsiFile(document);
        if (file == null || !file.isWritable())
            return;
        PsiElement element = file.findElementAt(offset);
        if (element == null)
            return;
        EditorHighlighter highlighter = ((EditorEx) editor).getHighlighter();
        HighlighterIterator iterator = highlighter.createIterator(offset);
        final FileType fileType = file.getFileType();
        BraceMatcher braceMatcher = BraceMatchingUtil.getBraceMatcher(fileType, iterator);
        boolean rBraceToken = braceMatcher.isRBraceToken(iterator, chars, fileType);
        final boolean isBrace = braceMatcher.isLBraceToken(iterator, chars, fileType) || rBraceToken;
        int lBraceOffset = -1;
        if (CodeInsightSettings.getInstance().REFORMAT_BLOCK_ON_RBRACE && rBraceToken && braceMatcher.isStructuralBrace(iterator, chars, fileType) && offset > 0) {
            lBraceOffset = BraceMatchingUtil.findLeftLParen(highlighter.createIterator(offset - 1), braceMatcher.getOppositeBraceTokenType(iterator.getTokenType()), editor.getDocument().getCharsSequence(), fileType);
        }
        if (element.getNode() != null && isBrace) {
            final int finalLBraceOffset = lBraceOffset;
            ApplicationManager.getApplication().runWriteAction(() -> {
                try {
                    int newOffset;
                    if (finalLBraceOffset != -1) {
                        RangeMarker marker = document.createRangeMarker(offset, offset + 1);
                        CodeStyleManager.getInstance(project).reformatRange(file, finalLBraceOffset, offset, true);
                        newOffset = marker.getStartOffset();
                        marker.dispose();
                    } else {
                        newOffset = CodeStyleManager.getInstance(project).adjustLineIndent(file, offset);
                    }
                    editor.getCaretModel().moveToOffset(newOffset + 1);
                    editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
                    editor.getSelectionModel().removeSelection();
                } catch (IncorrectOperationException e) {
                    LOG.error(e);
                }
            });
        }
    }
}
Also used : EditorEx(com.intellij.openapi.editor.ex.EditorEx) NontrivialBraceMatcher(com.intellij.codeInsight.highlighting.NontrivialBraceMatcher) BraceMatcher(com.intellij.codeInsight.highlighting.BraceMatcher) FileType(com.intellij.openapi.fileTypes.FileType) LanguageFileType(com.intellij.openapi.fileTypes.LanguageFileType) PsiFile(com.intellij.psi.PsiFile) IncorrectOperationException(com.intellij.util.IncorrectOperationException) PsiElement(com.intellij.psi.PsiElement) HighlighterIterator(com.intellij.openapi.editor.highlighter.HighlighterIterator) PsiDocumentManager(com.intellij.psi.PsiDocumentManager) EditorHighlighter(com.intellij.openapi.editor.highlighter.EditorHighlighter)

Example 30 with HighlighterIterator

use of com.intellij.openapi.editor.highlighter.HighlighterIterator in project intellij-community by JetBrains.

the class TypedHandler method handleRParen.

public static boolean handleRParen(@NotNull Editor editor, @NotNull FileType fileType, char charTyped) {
    if (!CodeInsightSettings.getInstance().AUTOINSERT_PAIR_BRACKET)
        return false;
    int offset = editor.getCaretModel().getOffset();
    if (offset == editor.getDocument().getTextLength())
        return false;
    HighlighterIterator iterator = ((EditorEx) editor).getHighlighter().createIterator(offset);
    if (iterator.atEnd())
        return false;
    if (iterator.getEnd() - iterator.getStart() != 1 || editor.getDocument().getCharsSequence().charAt(iterator.getStart()) != charTyped) {
        return false;
    }
    BraceMatcher braceMatcher = BraceMatchingUtil.getBraceMatcher(fileType, iterator);
    CharSequence text = editor.getDocument().getCharsSequence();
    if (!braceMatcher.isRBraceToken(iterator, text, fileType)) {
        return false;
    }
    IElementType tokenType = iterator.getTokenType();
    iterator.retreat();
    IElementType lparenTokenType = braceMatcher.getOppositeBraceTokenType(tokenType);
    int lparenthOffset = BraceMatchingUtil.findLeftmostLParen(iterator, lparenTokenType, text, fileType);
    if (lparenthOffset < 0) {
        if (braceMatcher instanceof NontrivialBraceMatcher) {
            for (IElementType t : ((NontrivialBraceMatcher) braceMatcher).getOppositeBraceTokenTypes(tokenType)) {
                if (t == lparenTokenType)
                    continue;
                lparenthOffset = BraceMatchingUtil.findLeftmostLParen(iterator, t, text, fileType);
                if (lparenthOffset >= 0)
                    break;
            }
        }
        if (lparenthOffset < 0)
            return false;
    }
    iterator = ((EditorEx) editor).getHighlighter().createIterator(lparenthOffset);
    boolean matched = BraceMatchingUtil.matchBrace(text, fileType, iterator, true, true);
    if (!matched)
        return false;
    EditorModificationUtil.moveCaretRelatively(editor, 1);
    return true;
}
Also used : IElementType(com.intellij.psi.tree.IElementType) NontrivialBraceMatcher(com.intellij.codeInsight.highlighting.NontrivialBraceMatcher) NontrivialBraceMatcher(com.intellij.codeInsight.highlighting.NontrivialBraceMatcher) BraceMatcher(com.intellij.codeInsight.highlighting.BraceMatcher) EditorEx(com.intellij.openapi.editor.ex.EditorEx) HighlighterIterator(com.intellij.openapi.editor.highlighter.HighlighterIterator)

Aggregations

HighlighterIterator (com.intellij.openapi.editor.highlighter.HighlighterIterator)83 EditorHighlighter (com.intellij.openapi.editor.highlighter.EditorHighlighter)36 EditorEx (com.intellij.openapi.editor.ex.EditorEx)33 IElementType (com.intellij.psi.tree.IElementType)33 Document (com.intellij.openapi.editor.Document)12 FileType (com.intellij.openapi.fileTypes.FileType)12 BraceMatcher (com.intellij.codeInsight.highlighting.BraceMatcher)9 TextRange (com.intellij.openapi.util.TextRange)8 Editor (com.intellij.openapi.editor.Editor)7 PsiElement (com.intellij.psi.PsiElement)6 TextAttributes (com.intellij.openapi.editor.markup.TextAttributes)5 PsiFile (com.intellij.psi.PsiFile)5 Language (com.intellij.lang.Language)4 CaretModel (com.intellij.openapi.editor.CaretModel)4 LexerEditorHighlighter (com.intellij.openapi.editor.ex.util.LexerEditorHighlighter)4 Project (com.intellij.openapi.project.Project)4 NontrivialBraceMatcher (com.intellij.codeInsight.highlighting.NontrivialBraceMatcher)3 Trinity (com.intellij.openapi.util.Trinity)3 ArrayList (java.util.ArrayList)3 LineMarkerInfo (com.intellij.codeInsight.daemon.LineMarkerInfo)2