findMatchingBracket function
Finds the matching {} / [] pair for the caret at cursor.
Looks at the character under the caret, or the one immediately before it
(so a caret after { still matches). Brackets inside JSON strings are
ignored.
Implementation
JsonBracketMatch? findMatchingBracket(String text, int cursor) {
if (text.isEmpty) return null;
final positions = <int>[];
if (cursor >= 0 && cursor < text.length) positions.add(cursor);
if (cursor > 0 && cursor <= text.length) positions.add(cursor - 1);
for (final pos in positions) {
if (pos < 0 || pos >= text.length) continue;
if (_isInsideJsonString(text, pos)) continue;
final ch = text[pos];
if (ch == '{' || ch == '[') {
final close = _scanForward(text, pos, ch, ch == '{' ? '}' : ']');
if (close != null) return JsonBracketMatch(open: pos, close: close);
} else if (ch == '}' || ch == ']') {
final open = _scanBackward(text, pos, ch == '}' ? '{' : '[', ch);
if (open != null) return JsonBracketMatch(open: open, close: pos);
}
}
return null;
}