int (@NotNull FileElement treeElement, @NotNull CharSequence text, boolean fromStart) { int patternIndex = fromStart ? 0 : text.length() - 1; int finalPatternIndex = fromStart ? text.length() - 1 : 0; int direction = fromStart ? 1 : -1; ASTNode leaf = fromStart ? TreeUtil.findFirstLeaf(treeElement, false) : TreeUtil.findLastLeaf(treeElement, false); int result = 0; while (leaf != null && (fromStart ? patternIndex <= finalPatternIndex : patternIndex >= finalPatternIndex)) { if (!(leaf instanceof ForeignLeafPsiElement)) { CharSequence chars = leaf.getChars(); if (chars.length() > 0) { int matchingLength = getLeafMatchingLength(chars, text, patternIndex, finalPatternIndex, direction); result += matchingLength; if (matchingLength != chars.length()) { break; } patternIndex += fromStart ? matchingLength : -matchingLength; } } leaf = fromStart ? TreeUtil.nextLeaf(leaf, false) : TreeUtil.prevLeaf(leaf, false); } return result; }