Java Code Examples for com.intellij.openapi.editor.highlighter.EditorHighlighter#createIterator()
The following examples show how to use
com.intellij.openapi.editor.highlighter.EditorHighlighter#createIterator() .
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: BraceHighlighter.java From HighlightBracketPair with Apache License 2.0 | 6 votes |
public BracePair findClosetBracePairInBraceTokens(int offset) { EditorHighlighter editorHighlighter = ((EditorEx) editor).getHighlighter(); boolean isBlockCaret = this.isBlockCaret(); List<Pair<IElementType, IElementType>> braceTokens = this.getSupportedBraceToken(); for (Pair<IElementType, IElementType> braceTokenPair : braceTokens) { HighlighterIterator leftTraverseIterator = editorHighlighter.createIterator(offset); HighlighterIterator rightTraverseIterator = editorHighlighter.createIterator(offset); int leftBraceOffset = BraceMatchingUtilAdapter.findLeftLParen( leftTraverseIterator, braceTokenPair.getLeft(), this.fileText, this.fileType, isBlockCaret); int rightBraceOffset = BraceMatchingUtilAdapter.findRightRParen( rightTraverseIterator, braceTokenPair.getRight(), this.fileText, this.fileType, isBlockCaret); if (leftBraceOffset != NON_OFFSET && rightBraceOffset != NON_OFFSET) { return new BracePair.BracePairBuilder(). leftType(braceTokenPair.getLeft()). rightType(braceTokenPair.getRight()). leftIterator(leftTraverseIterator). rightIterator(rightTraverseIterator).build(); } } return EMPTY_BRACE_PAIR; }
Example 2
Source File: BraceHighlighter.java From HighlightBracketPair with Apache License 2.0 | 6 votes |
public BracePair findClosetBracePairInStringSymbols(int offset) { if (offset < 0 || this.fileText == null || this.fileText.length() == 0) return EMPTY_BRACE_PAIR; EditorHighlighter editorHighlighter = ((EditorEx) editor).getHighlighter(); HighlighterIterator iterator = editorHighlighter.createIterator(offset); IElementType type = iterator.getTokenType(); boolean isBlockCaret = this.isBlockCaret(); if (!BraceMatchingUtilAdapter.isStringToken(type)) return EMPTY_BRACE_PAIR; int leftOffset = iterator.getStart(); int rightOffset = iterator.getEnd() - 1; if (!isBlockCaret && leftOffset == offset) return EMPTY_BRACE_PAIR; return new BracePair.BracePairBuilder(). leftType(DOUBLE_QUOTE). rightType(DOUBLE_QUOTE). leftOffset(leftOffset). rightOffset(rightOffset).build(); }
Example 3
Source File: ToggleCaseAction.java From consulo with Apache License 2.0 | 6 votes |
private static String toCase(Editor editor, int startOffset, int endOffset, final boolean lower) { CharSequence text = editor.getDocument().getImmutableCharSequence(); EditorHighlighter highlighter; if (editor instanceof EditorEx) { highlighter = ((EditorEx)editor).getHighlighter(); } else { highlighter = new EmptyEditorHighlighter(null); highlighter.setText(text); } HighlighterIterator iterator = highlighter.createIterator(startOffset); StringBuilder builder = new StringBuilder(endOffset - startOffset); while (!iterator.atEnd()) { int start = trim(iterator.getStart(), startOffset, endOffset); int end = trim(iterator.getEnd(), startOffset, endOffset); CharSequence fragment = text.subSequence(start, end); builder.append(iterator.getTokenType() == VALID_STRING_ESCAPE_TOKEN ? fragment : lower ? fragment.toString().toLowerCase(Locale.getDefault()) : fragment.toString().toUpperCase(Locale.getDefault())); if (end == endOffset) break; iterator.advance(); } return builder.toString(); }
Example 4
Source File: EnterInStringLiteralHandler.java From consulo with Apache License 2.0 | 6 votes |
private static boolean isInStringLiteral(@Nonnull Editor editor, @Nonnull DataContext dataContext, int offset) { Language language = EnterHandler.getLanguage(dataContext); if (offset > 0 && language != null) { QuoteHandler quoteHandler = TypedHandler.getLanguageQuoteHandler(language); if (quoteHandler == null) { FileType fileType = language.getAssociatedFileType(); quoteHandler = fileType != null ? TypedHandler.getQuoteHandlerForType(fileType) : null; } if (quoteHandler != null) { EditorHighlighter highlighter = ((EditorEx)editor).getHighlighter(); HighlighterIterator iterator = highlighter.createIterator(offset - 1); return StringEscapesTokenTypes.STRING_LITERAL_ESCAPES.contains(iterator.getTokenType()) || quoteHandler.isInsideLiteral(iterator); } } return false; }
Example 5
Source File: TodoItemNode.java From consulo with Apache License 2.0 | 6 votes |
private static void collectHighlights(@Nonnull List<? super HighlightedRegion> highlights, @Nonnull EditorHighlighter highlighter, int startOffset, int endOffset, int highlightOffsetShift) { HighlighterIterator iterator = highlighter.createIterator(startOffset); while (!iterator.atEnd()) { int start = Math.max(iterator.getStart(), startOffset); int end = Math.min(iterator.getEnd(), endOffset); if (start >= endOffset) break; TextAttributes attributes = iterator.getTextAttributes(); int fontType = attributes.getFontType(); if ((fontType & Font.BOLD) != 0) { // suppress bold attribute attributes = attributes.clone(); attributes.setFontType(fontType & ~Font.BOLD); } HighlightedRegion region = new HighlightedRegion(highlightOffsetShift + start - startOffset, highlightOffsetShift + end - startOffset, attributes); highlights.add(region); iterator.advance(); } }
Example 6
Source File: EditorTestUtil.java From consulo with Apache License 2.0 | 5 votes |
public static List<IElementType> getAllTokens(EditorHighlighter highlighter) { List<IElementType> tokens = new ArrayList<IElementType>(); HighlighterIterator iterator = highlighter.createIterator(0); while (!iterator.atEnd()) { tokens.add(iterator.getTokenType()); iterator.advance(); } return tokens; }
Example 7
Source File: EditorActionUtil.java From consulo with Apache License 2.0 | 5 votes |
/** * Finds out whether there's a boundary between two lexemes of different type at given offset. */ public static boolean isLexemeBoundary(@Nonnull Editor editor, int offset) { if (!(editor instanceof EditorEx) || offset <= 0 || offset >= editor.getDocument().getTextLength()) return false; if (CharArrayUtil.isEmptyOrSpaces(editor.getDocument().getImmutableCharSequence(), offset - 1, offset + 1)) return false; EditorHighlighter highlighter = ((EditorEx)editor).getHighlighter(); HighlighterIterator it = highlighter.createIterator(offset); if (it.getStart() != offset) { return false; } IElementType rightToken = it.getTokenType(); it.retreat(); IElementType leftToken = it.getTokenType(); return !Comparing.equal(leftToken, rightToken); }
Example 8
Source File: EditorPainter.java From consulo with Apache License 2.0 | 5 votes |
private void paintBorderEffect(EditorHighlighter highlighter) { HighlighterIterator it = highlighter.createIterator(myStartOffset); while (!it.atEnd() && it.getStart() < myEndOffset) { TextAttributes attributes = it.getTextAttributes(); EffectDescriptor borderDescriptor = getBorderDescriptor(attributes); if (borderDescriptor != null) { paintBorderEffect(it.getStart(), it.getEnd(), borderDescriptor); } it.advance(); } }
Example 9
Source File: RecentLocationsDataModel.java From consulo with Apache License 2.0 | 5 votes |
private void applySyntaxHighlighting(Project project, EditorEx editor, Document document, EditorColorsScheme colorsScheme, TextRange textRange, IdeDocumentHistoryImpl.PlaceInfo placeInfo) { EditorHighlighter editorHighlighter = EditorHighlighterFactory.getInstance().createEditorHighlighter(placeInfo.getFile(), colorsScheme, project); editorHighlighter.setEditor(new LightHighlighterClient(document, project)); editorHighlighter.setText(document.getText(TextRange.create(0, textRange.getEndOffset()))); int startOffset = textRange.getStartOffset(); for (HighlighterIterator iterator = editorHighlighter.createIterator(startOffset); !iterator.atEnd() && iterator.getEnd() <= textRange.getEndOffset(); iterator.advance()) { if (iterator.getStart() >= startOffset) { editor.getMarkupModel().addRangeHighlighter(iterator.getStart() - startOffset, iterator.getEnd() - startOffset, 999, iterator.getTextAttributes(), HighlighterTargetArea.EXACT_RANGE); } } }
Example 10
Source File: DustEnterHandler.java From Intellij-Dust with MIT License | 5 votes |
/** * Checks to see if {@code Enter} has been typed while the caret is between an open and close tag pair. * @return true if between open and close tags, false otherwise */ private static boolean isBetweenHbTags(Editor editor, PsiFile file, int offset) { if (offset == 0) return false; CharSequence chars = editor.getDocument().getCharsSequence(); if (chars.charAt(offset - 1) != '}') return false; EditorHighlighter highlighter = ((EditorEx)editor).getHighlighter(); HighlighterIterator iterator = highlighter.createIterator(offset - 1); final PsiElement openerElement = file.findElementAt(iterator.getStart()); PsiElement openTag = DustPsiUtil.findParentOpenTagElement(openerElement); if (openTag == null) { return false; } iterator.advance(); if (iterator.atEnd()) { // no more tokens, so certainly no close tag return false; } final PsiElement closerElement = file.findElementAt(iterator.getStart()); PsiElement closeTag = DustPsiUtil.findParentCloseTagElement(closerElement); // if we got this far, we're between open and close tags iff this is a close tag return closeTag != null; }
Example 11
Source File: EnterAfterUnmatchedBraceHandler.java From consulo with Apache License 2.0 | 4 votes |
/** * Calculates number of unmatched left braces before the given offset. * * @param editor target editor * @param offset target offset * @param fileType target file type * @return number of unmatched braces before the given offset; * negative value if it's not possible to perform the calculation or if there are no unmatched left braces before * the given offset */ protected static int getUnmatchedLBracesNumberBefore(Editor editor, int offset, FileType fileType) { if (offset == 0) { return -1; } CharSequence chars = editor.getDocument().getCharsSequence(); if (chars.charAt(offset - 1) != '{') { return -1; } EditorHighlighter highlighter = ((EditorEx)editor).getHighlighter(); HighlighterIterator iterator = highlighter.createIterator(offset - 1); BraceMatcher braceMatcher = BraceMatchingUtil.getBraceMatcher(fileType, iterator); if (!braceMatcher.isLBraceToken(iterator, chars, fileType) || !braceMatcher.isStructuralBrace(iterator, chars, fileType)) { return -1; } Language language = iterator.getTokenType().getLanguage(); iterator = highlighter.createIterator(0); int lBracesBeforeOffset = 0; int lBracesAfterOffset = 0; int rBracesBeforeOffset = 0; int rBracesAfterOffset = 0; for (; !iterator.atEnd(); iterator.advance()) { IElementType tokenType = iterator.getTokenType(); if (!tokenType.getLanguage().equals(language) || !braceMatcher.isStructuralBrace(iterator, chars, fileType)) { continue; } boolean beforeOffset = iterator.getStart() < offset; if (braceMatcher.isLBraceToken(iterator, chars, fileType)) { if (beforeOffset) { lBracesBeforeOffset++; } else { lBracesAfterOffset++; } } else if (braceMatcher.isRBraceToken(iterator, chars, fileType)) { if (beforeOffset) { rBracesBeforeOffset++; } else { rBracesAfterOffset++; } } } return lBracesBeforeOffset - rBracesBeforeOffset - (rBracesAfterOffset - lBracesAfterOffset); }
Example 12
Source File: BaseIndentEnterHandler.java From consulo with Apache License 2.0 | 4 votes |
@Override public Result preprocessEnter( @Nonnull final PsiFile file, @Nonnull final Editor editor, @Nonnull final Ref<Integer> caretOffset, @Nonnull final Ref<Integer> caretAdvance, @Nonnull final DataContext dataContext, final EditorActionHandler originalHandler) { Result res = shouldSkipWithResult(file, editor, dataContext); if (res != null) { return res; } final Document document = editor.getDocument(); int caret = editor.getCaretModel().getOffset(); final int lineNumber = document.getLineNumber(caret); final int lineStartOffset = document.getLineStartOffset(lineNumber); final int previousLineStartOffset = lineNumber > 0 ? document.getLineStartOffset(lineNumber - 1) : lineStartOffset; final EditorHighlighter highlighter = ((EditorEx)editor).getHighlighter(); final HighlighterIterator iterator = highlighter.createIterator(caret - 1); final IElementType type = getNonWhitespaceElementType(iterator, lineStartOffset, previousLineStartOffset); final CharSequence editorCharSequence = document.getCharsSequence(); final CharSequence lineIndent = editorCharSequence.subSequence(lineStartOffset, EditorActionUtil.findFirstNonSpaceOffsetOnTheLine(document, lineNumber)); // Enter in line comment if (type == myLineCommentType) { final String restString = editorCharSequence.subSequence(caret, document.getLineEndOffset(lineNumber)).toString(); if (!StringUtil.isEmptyOrSpaces(restString)) { final String linePrefix = lineIndent + myLineCommentPrefix; EditorModificationUtil.insertStringAtCaret(editor, "\n" + linePrefix); editor.getCaretModel().moveToLogicalPosition(new LogicalPosition(lineNumber + 1, linePrefix.length())); return Result.Stop; } else if (iterator.getStart() < lineStartOffset) { EditorModificationUtil.insertStringAtCaret(editor, "\n" + lineIndent); return Result.Stop; } } if (!myWorksWithFormatter && LanguageFormatting.INSTANCE.forLanguage(myLanguage) != null) { return Result.Continue; } else { if (myIndentTokens.contains(type)) { final String newIndent = getNewIndent(file, document, lineIndent); EditorModificationUtil.insertStringAtCaret(editor, "\n" + newIndent); return Result.Stop; } EditorModificationUtil.insertStringAtCaret(editor, "\n" + lineIndent); editor.getCaretModel().moveToLogicalPosition(new LogicalPosition(lineNumber + 1, calcLogicalLength(editor, lineIndent))); return Result.Stop; } }
Example 13
Source File: TypedHandler.java From consulo with Apache License 2.0 | 4 votes |
private static void indentBrace(@Nonnull final Project project, @Nonnull 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) { DefaultRawTypedHandler handler = ((TypedActionImpl)TypedAction.getInstance()).getDefaultRawTypedHandler(); handler.beginUndoablePostProcessing(); 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); } }); } } }
Example 14
Source File: SyntaxInfoBuilder.java From consulo with Apache License 2.0 | 4 votes |
HighlighterRangeIterator(@Nonnull EditorHighlighter highlighter, int startOffset, int endOffset) { myStartOffset = startOffset; myEndOffset = endOffset; myIterator = highlighter.createIterator(startOffset); }
Example 15
Source File: InjectionRegistrarImpl.java From consulo with Apache License 2.0 | 4 votes |
@Nonnull private static List<InjectedLanguageUtil.TokenInfo> obtainHighlightTokensFromLexer(@Nonnull LanguageVersion languageVersion, @Nonnull CharSequence outChars, @Nonnull VirtualFileWindow virtualFile, @Nonnull Project project, @Nonnull List<? extends PlaceInfo> placeInfos) { VirtualFile file = (VirtualFile)virtualFile; FileType fileType = file.getFileType(); EditorHighlighterProvider provider = FileTypeEditorHighlighterProviders.INSTANCE.forFileType(fileType); EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme(); EditorHighlighter highlighter = provider.getEditorHighlighter(project, fileType, file, scheme); highlighter.setText(outChars); HighlighterIterator iterator = highlighter.createIterator(0); int hostNum = -1; int prevHostEndOffset = 0; LiteralTextEscaper escaper = null; int prefixLength = 0; int suffixLength = 0; TextRange rangeInsideHost = null; int shredEndOffset = -1; List<InjectedLanguageUtil.TokenInfo> tokens = new ArrayList<>(outChars.length() / 5); // avg. token per 5 chars while (!iterator.atEnd()) { IElementType tokenType = iterator.getTokenType(); TextRange range = new ProperTextRange(iterator.getStart(), iterator.getEnd()); while (range != null && !range.isEmpty()) { if (range.getStartOffset() >= shredEndOffset) { hostNum++; PlaceInfo info = placeInfos.get(hostNum); shredEndOffset = info.rangeInDecodedPSI.getEndOffset(); prevHostEndOffset = range.getStartOffset(); escaper = info.myEscaper; rangeInsideHost = info.rangeInHostElement; prefixLength = info.prefix.length(); suffixLength = info.suffix.length(); } //in prefix/suffix or spills over to next fragment if (range.getStartOffset() < prevHostEndOffset + prefixLength) { range = new UnfairTextRange(prevHostEndOffset + prefixLength, range.getEndOffset()); } TextRange spilled = null; if (range.getEndOffset() > shredEndOffset - suffixLength) { spilled = new UnfairTextRange(shredEndOffset, range.getEndOffset()); range = new UnfairTextRange(range.getStartOffset(), shredEndOffset - suffixLength); } if (!range.isEmpty()) { int start = escaper.getOffsetInHost(range.getStartOffset() - prevHostEndOffset - prefixLength, rangeInsideHost); if (start == -1) start = rangeInsideHost.getStartOffset(); int end = escaper.getOffsetInHost(range.getEndOffset() - prevHostEndOffset - prefixLength, rangeInsideHost); if (end == -1) { end = rangeInsideHost.getEndOffset(); prevHostEndOffset = shredEndOffset; } ProperTextRange rangeInHost = new ProperTextRange(start, end); tokens.add(new InjectedLanguageUtil.TokenInfo(tokenType, rangeInHost, hostNum, iterator.getTextAttributes())); } range = spilled; } iterator.advance(); } return tokens; }