int (@NotNull Editor editor, int offset, @NotNull IElementType lt, @NotNull IElementType gt, @NotNull TokenSet invalidInsideReference, boolean forwardDirection) { HighlighterIterator iterator = editor.getHighlighter().createIterator(offset); if (!forwardDirection && iterator.getTokenType() != gt) return -1; while ((forwardDirection && iterator.getStart() > 0 || !forwardDirection && !iterator.atEnd()) && !invalidInsideReference.contains(iterator.getTokenType())) { incLookup(!forwardDirection /*we're rewinding*/, iterator); } if ((forwardDirection || !iterator.atEnd()) && invalidInsideReference.contains(iterator.getTokenType())) { incLookup(forwardDirection, iterator); } int balance = 0; while (!iterator.atEnd() && balance >= 0) { final IElementType tokenType = iterator.getTokenType(); if (tokenType == lt) { if (forwardDirection) balance++; else balance--; } else if (tokenType == gt) { if (forwardDirection) balance--; else balance++; } else if (invalidInsideReference.contains(tokenType)) { break; } incLookup(forwardDirection, iterator); } return balance; }