private int endOfBalancedChunk(String expression, int maxSize) {
        int chunkSize = 0;
        int i = 0;
        int nesting = 0;
        while (i < maxSize && i < expression.length()) {
            if (expression.charAt(i) == '\t') return chunkSize;
            if (expression.charAt(i) == '(') nesting++;
            if (expression.charAt(i) == ')') nesting--;
            if (nesting < 0) return chunkSize;
            if (nesting == 0 && ( expression.charAt(i)==')' || expression.charAt(i)==','))
                chunkSize = i;
            i++;
        }
        return chunkSize;
    }
Returns the position of the end of a balanced chunk of at most the given size, or 0 if there is no such chunk
vespajlib/src/main/java/com/yahoo/text/ExpressionFormatter.java