Search in sources :

Example 6 with BraceMatcher

use of com.intellij.codeInsight.highlighting.BraceMatcher 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 7 with BraceMatcher

use of com.intellij.codeInsight.highlighting.BraceMatcher 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)

Example 8 with BraceMatcher

use of com.intellij.codeInsight.highlighting.BraceMatcher in project intellij-community by JetBrains.

the class BackspaceHandler method handleBackspace.

protected boolean handleBackspace(Editor editor, Caret caret, DataContext dataContext, boolean toWordStart) {
    Project project = CommonDataKeys.PROJECT.getData(dataContext);
    if (project == null)
        return false;
    PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);
    if (file == null)
        return false;
    if (editor.getSelectionModel().hasSelection())
        return false;
    int offset = DocumentUtil.getPreviousCodePointOffset(editor.getDocument(), editor.getCaretModel().getOffset());
    if (offset < 0)
        return false;
    CharSequence chars = editor.getDocument().getCharsSequence();
    int c = Character.codePointAt(chars, offset);
    final Editor injectedEditor = TypedHandler.injectedEditorIfCharTypedIsSignificant(c, editor, file);
    final Editor originalEditor = editor;
    if (injectedEditor != editor) {
        int injectedOffset = injectedEditor.getCaretModel().getOffset();
        if (isOffsetInsideInjected(injectedEditor, injectedOffset)) {
            file = PsiDocumentManager.getInstance(project).getPsiFile(injectedEditor.getDocument());
            editor = injectedEditor;
            offset = DocumentUtil.getPreviousCodePointOffset(injectedEditor.getDocument(), injectedOffset);
        }
    }
    final BackspaceHandlerDelegate[] delegates = Extensions.getExtensions(BackspaceHandlerDelegate.EP_NAME);
    if (!toWordStart && Character.isBmpCodePoint(c)) {
        for (BackspaceHandlerDelegate delegate : delegates) {
            delegate.beforeCharDeleted((char) c, file, editor);
        }
    }
    FileType fileType = file.getFileType();
    final QuoteHandler quoteHandler = TypedHandler.getQuoteHandler(file, editor);
    HighlighterIterator hiterator = ((EditorEx) editor).getHighlighter().createIterator(offset);
    boolean wasClosingQuote = quoteHandler != null && quoteHandler.isClosingQuote(hiterator, offset);
    myOriginalHandler.execute(originalEditor, caret, dataContext);
    if (!toWordStart && Character.isBmpCodePoint(c)) {
        for (BackspaceHandlerDelegate delegate : delegates) {
            if (delegate.charDeleted((char) c, file, editor)) {
                return true;
            }
        }
    }
    if (offset >= editor.getDocument().getTextLength())
        return true;
    chars = editor.getDocument().getCharsSequence();
    if ((c == '(' || c == '[' || c == '{') && CodeInsightSettings.getInstance().AUTOINSERT_PAIR_BRACKET) {
        char c1 = chars.charAt(offset);
        if (c1 != getRightChar((char) c))
            return true;
        HighlighterIterator iterator = ((EditorEx) editor).getHighlighter().createIterator(offset);
        BraceMatcher braceMatcher = BraceMatchingUtil.getBraceMatcher(fileType, iterator);
        if (!braceMatcher.isLBraceToken(iterator, chars, fileType) && !braceMatcher.isRBraceToken(iterator, chars, fileType)) {
            return true;
        }
        int rparenOffset = BraceMatchingUtil.findRightmostRParen(iterator, iterator.getTokenType(), chars, fileType);
        if (rparenOffset >= 0) {
            iterator = ((EditorEx) editor).getHighlighter().createIterator(rparenOffset);
            boolean matched = BraceMatchingUtil.matchBrace(chars, fileType, iterator, false);
            if (matched)
                return true;
        }
        editor.getDocument().deleteString(offset, offset + 1);
    } else if ((c == '"' || c == '\'' || c == '`') && CodeInsightSettings.getInstance().AUTOINSERT_PAIR_QUOTE) {
        char c1 = chars.charAt(offset);
        if (c1 != c)
            return true;
        if (wasClosingQuote)
            return true;
        HighlighterIterator iterator = ((EditorEx) editor).getHighlighter().createIterator(offset);
        if (quoteHandler == null || !quoteHandler.isOpeningQuote(iterator, offset))
            return true;
        editor.getDocument().deleteString(offset, offset + 1);
    }
    return true;
}
Also used : BraceMatcher(com.intellij.codeInsight.highlighting.BraceMatcher) EditorEx(com.intellij.openapi.editor.ex.EditorEx) Project(com.intellij.openapi.project.Project) FileType(com.intellij.openapi.fileTypes.FileType) PsiFile(com.intellij.psi.PsiFile) Editor(com.intellij.openapi.editor.Editor) HighlighterIterator(com.intellij.openapi.editor.highlighter.HighlighterIterator)

Example 9 with BraceMatcher

use of com.intellij.codeInsight.highlighting.BraceMatcher in project intellij-community by JetBrains.

the class BraceMatcherBasedSelectioner method select.

@Override
public List<TextRange> select(final PsiElement e, final CharSequence editorText, final int cursorOffset, final Editor editor) {
    final VirtualFile file = e.getContainingFile().getVirtualFile();
    final FileType fileType = file == null ? null : file.getFileType();
    if (fileType == null)
        return super.select(e, editorText, cursorOffset, editor);
    final int textLength = editorText.length();
    final TextRange totalRange = e.getTextRange();
    final HighlighterIterator iterator = ((EditorEx) editor).getHighlighter().createIterator(totalRange.getStartOffset());
    final BraceMatcher braceMatcher = BraceMatchingUtil.getBraceMatcher(fileType, iterator);
    final ArrayList<TextRange> result = new ArrayList<>();
    final LinkedList<Trinity<Integer, Integer, IElementType>> stack = new LinkedList<>();
    while (!iterator.atEnd() && iterator.getStart() < totalRange.getEndOffset()) {
        final Trinity<Integer, Integer, IElementType> last;
        if (braceMatcher.isLBraceToken(iterator, editorText, fileType)) {
            stack.addLast(Trinity.create(iterator.getStart(), iterator.getEnd(), iterator.getTokenType()));
        } else if (braceMatcher.isRBraceToken(iterator, editorText, fileType) && !stack.isEmpty() && braceMatcher.isPairBraces((last = stack.getLast()).third, iterator.getTokenType())) {
            stack.removeLast();
            result.addAll(expandToWholeLine(editorText, new TextRange(last.first, iterator.getEnd())));
            int bodyStart = last.second;
            int bodyEnd = iterator.getStart();
            while (bodyStart < textLength && Character.isWhitespace(editorText.charAt(bodyStart))) bodyStart++;
            while (bodyEnd > 0 && bodyStart < bodyEnd && Character.isWhitespace(editorText.charAt(bodyEnd - 1))) bodyEnd--;
            result.addAll(expandToWholeLine(editorText, new TextRange(bodyStart, bodyEnd)));
        }
        iterator.advance();
    }
    result.add(e.getTextRange());
    return result;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) BraceMatcher(com.intellij.codeInsight.highlighting.BraceMatcher) Trinity(com.intellij.openapi.util.Trinity) ArrayList(java.util.ArrayList) TextRange(com.intellij.openapi.util.TextRange) LinkedList(java.util.LinkedList) IElementType(com.intellij.psi.tree.IElementType) FileType(com.intellij.openapi.fileTypes.FileType) HighlighterIterator(com.intellij.openapi.editor.highlighter.HighlighterIterator)

Example 10 with BraceMatcher

use of com.intellij.codeInsight.highlighting.BraceMatcher in project intellij-plugins by JetBrains.

the class CfmlBraceMatcher method isRBraceToken.

public boolean isRBraceToken(HighlighterIterator iterator, CharSequence fileText, FileType fileType) {
    final IElementType tokenType = iterator.getTokenType();
    PairedBraceMatcher matcher = LanguageBraceMatching.INSTANCE.forLanguage(tokenType.getLanguage());
    if (matcher != null) {
        BracePair[] pairs = matcher.getPairs();
        for (BracePair pair : pairs) {
            if (pair.getRightBraceType() == tokenType)
                return true;
        }
    }
    if (!tokenType.getLanguage().equals(CfmlLanguage.INSTANCE)) {
        FileType tokenFileType = iterator.getTokenType().getLanguage().getAssociatedFileType();
        if (tokenFileType != null && tokenFileType != CfmlFileType.INSTANCE) {
            for (FileTypeExtensionPoint<BraceMatcher> ext : Extensions.getExtensions(BraceMatcher.EP_NAME)) {
                if (ext.filetype != null && ext.filetype.equals(tokenFileType.getName())) {
                    return ext.getInstance().isRBraceToken(iterator, fileText, tokenFileType instanceof XmlFileType ? StdFileTypes.HTML : tokenFileType);
                }
            }
        }
    }
    for (BracePair pair : PAIRS) {
        if (pair.getRightBraceType() == tokenType)
            return true;
    }
    return ((tokenType.equals(CfmlTokenTypes.CLOSER)) && findBeginTag(fileText, iterator)) || (tokenType.equals(CfmlTokenTypes.R_ANGLEBRACKET) && !CfmlUtil.isEndTagRequired(getTagName(fileText, iterator), null) && !findEndTag(fileText, iterator));
}
Also used : IElementType(com.intellij.psi.tree.IElementType) PairedBraceMatcher(com.intellij.lang.PairedBraceMatcher) PairedBraceMatcher(com.intellij.lang.PairedBraceMatcher) BraceMatcher(com.intellij.codeInsight.highlighting.BraceMatcher) XmlFileType(com.intellij.ide.highlighter.XmlFileType) FileType(com.intellij.openapi.fileTypes.FileType) CfmlFileType(com.intellij.coldFusion.model.files.CfmlFileType) BracePair(com.intellij.lang.BracePair) XmlFileType(com.intellij.ide.highlighter.XmlFileType)

Aggregations

BraceMatcher (com.intellij.codeInsight.highlighting.BraceMatcher)12 HighlighterIterator (com.intellij.openapi.editor.highlighter.HighlighterIterator)9 FileType (com.intellij.openapi.fileTypes.FileType)9 IElementType (com.intellij.psi.tree.IElementType)8 EditorEx (com.intellij.openapi.editor.ex.EditorEx)6 NontrivialBraceMatcher (com.intellij.codeInsight.highlighting.NontrivialBraceMatcher)3 CfmlFileType (com.intellij.coldFusion.model.files.CfmlFileType)3 XmlFileType (com.intellij.ide.highlighter.XmlFileType)3 BracePair (com.intellij.lang.BracePair)3 PairedBraceMatcher (com.intellij.lang.PairedBraceMatcher)3 EditorHighlighter (com.intellij.openapi.editor.highlighter.EditorHighlighter)3 TextRange (com.intellij.openapi.util.TextRange)3 Trinity (com.intellij.openapi.util.Trinity)3 LinkedList (java.util.LinkedList)3 FoldingDescriptor (com.intellij.lang.folding.FoldingDescriptor)2 LexerEditorHighlighter (com.intellij.openapi.editor.ex.util.LexerEditorHighlighter)2 PsiFile (com.intellij.psi.PsiFile)2 Language (com.intellij.lang.Language)1 Document (com.intellij.openapi.editor.Document)1 Editor (com.intellij.openapi.editor.Editor)1