Skip to content

Visual Studio Code, rebuilt in Rust

Rust
38.9 KB
Raw Blame
//! Bracket pair colorization: the bracket tokens of a language (bracketPairsTree/brackets.ts), the
//! tokenizer over the TextMate tokens (tokenizer.ts), the pair parser (parser.ts) and the nesting levels
//! `collectBrackets` hands to the decoration provider (bracketPairsTree.ts).

mod edits;
mod ids;
mod length;
mod tree;

use std::collections::HashMap;
use std::ops::Range;
use std::sync::Arc;

use serde_json::Value;
use textmate::{StandardTokenType, Style};

use edits::{TextEditInfo, combine_text_edit_infos};
use ids::BracketIds;
use length::Length;
use tree::Node;

/// The brackets of one language: `LanguageBracketsConfiguration` turned into `BracketTokens`.
pub struct LanguageBrackets {
    tokens: HashMap<String, Arc<BracketToken>>,
    regex: Option<onig::Regex>,
}

struct BracketToken {
    opening: bool,
    /// `languageId:::text` of the bracket, or of the first opening bracket a closing one closes.
    id: String,
    /// The key of `id`.
    key: usize,
    /// The opening brackets this one opens or closes.
    ids: BracketIds,
    /// The opening brackets a closing one closes as a colorized pair.
    colorized_openings: BracketIds,
}

impl LanguageBrackets {
    /// From a language configuration: `brackets`, and `colorizedBracketPairs`, which defaults to the
    /// brackets except `<>`. Every colorized pair is a bracket pair too.
    pub fn new(language: &str, config: &Value) -> Self {
        let brackets = character_pairs(&config["brackets"]).unwrap_or_default();
        let colorized = character_pairs(&config["colorizedBracketPairs"])
            .unwrap_or_else(|| brackets.iter().filter(|(open, close)| !(open == "<" && close == ">")).cloned().collect());
        let id = |text: &str| format!("{language}:::{text}");
        // Insertion ordered, as the CachedFunction maps of LanguageBracketsConfiguration.
        let mut openings: Vec<&str> = Vec::new();
        let mut closings: Vec<(&str, Vec<String>, Vec<String>)> = Vec::new();
        for (index, (open, close)) in brackets.iter().chain(&colorized).enumerate() {
            if !openings.contains(&open.as_str()) {
                openings.push(open);
            }
            let position = match closings.iter().position(|(text, ..)| text == close) {
                Some(position) => position,
                None => {
                    closings.push((close, Vec::new(), Vec::new()));
                    closings.len() - 1
                }
            };
            let (_, opened, colorized_opened) = &mut closings[position];
            if !opened.contains(&id(open)) {
                opened.push(id(open));
            }
            if index >= brackets.len() && !colorized_opened.contains(&id(open)) {
                colorized_opened.push(id(open));
            }
        }
        let mut tokens = HashMap::new();
        for open in openings {
            let token = BracketToken { opening: true, id: id(open), key: ids::key(&id(open)), ids: BracketIds::of(&[id(open)]), colorized_openings: BracketIds::EMPTY };
            tokens.insert(open.to_string(), Arc::new(token));
        }
        for (close, opened, colorized_openings) in closings {
            let token = BracketToken { opening: false, id: opened[0].clone(), key: ids::key(&opened[0]), ids: BracketIds::of(&opened), colorized_openings: BracketIds::of(&colorized_openings) };
            tokens.insert(close.to_string(), Arc::new(token));
        }
        let mut texts: Vec<&String> = tokens.keys().collect();
        texts.sort();
        texts.reverse();
        let pattern = texts.iter().map(|text| bracket_pattern(text)).collect::<Vec<_>>().join("|");
        let regex = (!texts.is_empty()).then(|| {
            onig::Regex::with_options(&pattern, onig::RegexOptions::REGEX_OPTION_IGNORECASE, onig::Syntax::default()).expect("escaped brackets compile")
        });
        LanguageBrackets { tokens, regex }
    }

    /// `BracketTokens.getToken`: the map holds the configured texts, the lookup is lower case.
    fn token(&self, text: &str) -> Option<&Arc<BracketToken>> {
        self.tokens.get(&text.to_lowercase())
    }

    /// `ClosingBracketKind.closes`: `close` is a closing bracket of the opening bracket `open`.
    pub fn closes(&self, close: &str, open: &str) -> bool {
        let (Some(close), Some(open)) = (self.token(close), self.token(open)) else { return false };
        !close.opening && close.ids.has(open.key)
    }

    /// `text.replace(getBracketRegExp({ global: true }), '')`: the text without any bracket.
    pub fn strip(&self, text: &str) -> String {
        match &self.regex {
            Some(regex) => regex.replace_all(text, ""),
            None => text.to_string(),
        }
    }
}

/// `_extractValidBrackets`: the `[open, close]` string pairs of an array, empty strings dropped
/// (`filterValidBrackets`); `None` when the key is not an array.
pub(crate) fn character_pairs(value: &Value) -> Option<Vec<(String, String)>> {
    let pairs = value.as_array()?.iter().filter_map(|pair| match pair.as_array()?.as_slice() {
        [Value::String(open), Value::String(close)] if !open.is_empty() && !close.is_empty() => Some((open.clone(), close.clone())),
        _ => None,
    });
    Some(pairs.collect())
}

/// `prepareBracketForRegExp`: escaped, with word boundaries where the bracket starts or ends with a
/// word character or space (#132162, #150440).
pub(crate) fn bracket_pattern(text: &str) -> String {
    let mut escaped = escape_regex(text);
    let word = |c: Option<char>| c.is_some_and(|c| c.is_ascii_alphanumeric() || c == '_' || c == ' ');
    if word(text.chars().next()) {
        escaped.insert_str(0, "\\b");
    }
    if word(text.chars().last()) {
        escaped.push_str("\\b");
    }
    escaped
}

/// `escapeRegExpCharacters`.
pub(crate) fn escape_regex(text: &str) -> String {
    let mut escaped = String::new();
    for c in text.chars() {
        if "\\{}*+?|^$.[]()".contains(c) {
            escaped.push('\\');
        }
        escaped.push(c);
    }
    escaped
}

/// A token of a line as the bracket tokenizer reads its metadata.
#[derive(Clone, Copy)]
pub struct Span<'a> {
    pub end: usize,
    pub language: &'a str,
    pub token_type: StandardTokenType,
    pub balanced_brackets: bool,
    pub style: Style,
}

impl Span<'_> {
    fn same_metadata(&self, other: &Span) -> bool {
        (self.language, self.token_type, self.balanced_brackets, self.style) == (other.language, other.token_type, other.balanced_brackets, other.style)
    }
}

/// A bracket to color: `level` indexes the bracket colors, `invalid` takes the unexpected bracket color.
#[derive(Clone, Debug, PartialEq)]
pub struct Bracket {
    pub range: Range<usize>,
    pub level: isize,
    pub invalid: bool,
}

/// A bracket's line and byte range in it.
pub type BracketRange = (usize, Range<usize>);

/// A pair of brackets; `close` is `None` for an opening bracket nothing closes. `end` (line, byte) is where its
/// range ends: after `close`, else where its parse ended. `level` counts the pairs around it, colorized or not
/// (`collectBracketPairs`).
pub struct Pair {
    pub open: BracketRange,
    pub close: Option<BracketRange>,
    pub end: (usize, usize),
    pub level: usize,
}

/// A bracket of a pair (`IFoundBracket`): `key` is the `languageId:::text` of the bracket, or of the first
/// opening bracket a closing one closes.
pub struct PairBracket {
    pub range: BracketRange,
    pub opening: bool,
    pub key: String,
}

/// The bracket tree of a document (bracketPairsTree.ts): the colorized brackets of a line
/// (`getBracketsInRange(range, true)`), the pairs that touch a range, outer pairs first (`getBracketPairsInRange`),
/// and every bracket of a pair in document order (`getFirstBracketAfter`/`Before` skip unexpected closings).
#[derive(Clone)]
pub struct DocumentBrackets {
    root: Arc<Node>,
}

impl DocumentBrackets {
    #[cfg(test)]
    pub fn new(lines: &[(&str, Vec<Span>)], languages: &HashMap<String, LanguageBrackets>) -> Self {
        let found: Vec<_> = lines.iter().map(|(text, spans)| line_brackets(text, spans, languages)).collect();
        let found: Vec<_> = found.iter().map(Vec::as_slice).collect();
        let lengths: Vec<_> = lines.iter().map(|(text, _)| text.len()).collect();
        DocumentBrackets { root: tree::parse_document(&found, &lengths, &[], None) }
    }

    /// The colorized brackets of line `line`.
    pub fn line(&self, line: usize) -> Vec<Bracket> {
        let mut found = Vec::new();
        collect_brackets(&self.root, Length::ZERO, (Length::new(line, 0), Length::new(line, usize::MAX)), 0, false, &mut found);
        found.into_iter().filter(|(start, _)| start.lines == line).map(|(_, bracket)| bracket).collect()
    }

    /// The pairs whose range touches the one from (line, byte) `from` to `to`.
    pub fn pairs_in(&self, from: (usize, usize), to: (usize, usize)) -> Vec<Pair> {
        let mut pairs = Vec::new();
        collect_pairs(&self.root, Length::ZERO, (Length::new(from.0, from.1), Length::new(to.0, to.1)), 0, &mut pairs);
        pairs
    }

    /// The pairs that touch lines `lines`.
    pub fn pairs_in_lines(&self, lines: Range<usize>) -> Vec<Pair> {
        match lines.is_empty() {
            true => Vec::new(),
            false => self.pairs_in((lines.start, 0), (lines.end - 1, usize::MAX)),
        }
    }

    /// `matchBracket`: the closed pair with a bracket that touches the position (line, byte), the
    /// bracket starting last winning.
    pub fn match_bracket(&self, line: usize, offset: usize) -> Option<[BracketRange; 2]> {
        let touches = |(bracket_line, range): &BracketRange| *bracket_line == line && range.start <= offset && offset <= range.end;
        let mut best: Option<(BracketRange, [BracketRange; 2])> = None;
        for pair in self.pairs_in((line, offset), (line, offset)) {
            let Some(close) = pair.close else { continue };
            let bracket = if touches(&pair.open) {
                pair.open.clone()
            } else if touches(&close) {
                close.clone()
            } else {
                continue;
            };
            if best.as_ref().is_none_or(|(best, _)| (bracket.0, bracket.1.start) >= (best.0, best.1.start)) {
                best = Some((bracket, [pair.open, close]));
            }
        }
        best.map(|(_, pair)| pair)
    }

    /// `findNextBracket` (`getFirstBracketAfter`): the first bracket of a pair that ends after the position (line, byte).
    pub fn next_bracket(&self, line: usize, offset: usize) -> Option<BracketRange> {
        first_bracket_after(&self.root, Length::ZERO, Length::new(line, offset))
    }

    /// `findEnclosingBrackets`: the innermost closed pair strictly around the position (line, byte).
    pub fn enclosing_brackets(&self, line: usize, offset: usize) -> Option<[BracketRange; 2]> {
        self.pairs_in((line, offset), (line, offset)).into_iter().rev().find_map(|pair| {
            let close = pair.close?;
            let after_open = (line, offset) > (pair.open.0, pair.open.1.start);
            let before_close = (line, offset) < (close.0, close.1.end);
            (after_open && before_close).then_some([pair.open, close])
        })
    }

    /// `hasUnmatchedClosingBracketAfter`: a closing bracket of the opening bracket `open` at or after the position
    /// (line, byte) closes none of the brackets open around it.
    pub fn has_unmatched_closing_after(&self, brackets: &LanguageBrackets, open: &str, line: usize, offset: usize) -> bool {
        let Some(token) = brackets.token(open).filter(|token| token.opening) else { return false };
        tree::has_unmatched_closing_after(&self.root, Length::new(line, offset), &token.ids)
    }

    /// Every bracket of a pair, in document order.
    pub fn pair_brackets(&self) -> Vec<PairBracket> {
        let mut brackets = Vec::new();
        collect_pair_brackets(&self.root, Length::ZERO, &mut brackets);
        brackets
    }
}

/// Each line's brackets until its text or tokens change, and the bracket tree over them with the edits since its
/// parse (`queuedTextEdits`).
#[derive(Default)]
pub struct BracketCache {
    pub lines: Vec<Option<Vec<LineBracket>>>,
    tree: Option<DocumentBrackets>,
    edits: Vec<TextEditInfo>,
}

impl BracketCache {
    pub fn new(line_count: usize) -> Self {
        BracketCache { lines: vec![None; line_count], ..BracketCache::default() }
    }

    /// `handleContentChanged` after lines `start..=end` were replaced by `new_line_count` lines.
    pub fn accept_edit(&mut self, start: usize, end: usize, new_line_count: usize) {
        self.lines.splice(start..=end, (0..new_line_count).map(|_| None));
        let edit = TextEditInfo { start: Length::new(start, 0), end: Length::new(end + 1, 0), new_length: Length::new(new_line_count, 0) };
        self.edits = combine_text_edit_infos(&self.edits, &[edit]);
    }

    /// The tree over the brackets of `lines`, `read_line` reading those of a line whose text or tokens changed.
    /// A line read again is an edit that keeps its length (`handleDidChangeTokens`).
    pub fn document(&mut self, lines: &[String], mut read_line: impl FnMut(usize) -> Vec<LineBracket>) -> DocumentBrackets {
        let mut read_again: Vec<TextEditInfo> = Vec::new();
        for (index, brackets) in self.lines.iter_mut().enumerate() {
            if brackets.is_some() {
                continue;
            }
            *brackets = Some(read_line(index));
            match read_again.last_mut() {
                Some(edit) if edit.end == Length::new(index, 0) => {
                    edit.end = Length::new(index + 1, 0);
                    edit.new_length.lines += 1;
                }
                _ => read_again.push(TextEditInfo { start: Length::new(index, 0), end: Length::new(index + 1, 0), new_length: Length::new(1, 0) }),
            }
        }
        let edits = combine_text_edit_infos(&std::mem::take(&mut self.edits), &read_again);
        if self.tree.is_none() || !edits.is_empty() {
            let found: Vec<_> = self.lines.iter().map(|brackets| brackets.as_deref().expect("every line's brackets were just read")).collect();
            let lengths: Vec<_> = lines.iter().map(String::len).collect();
            let previous = self.tree.take().map(|tree| tree.root);
            self.tree = Some(DocumentBrackets { root: tree::parse_document(&found, &lengths, &edits, previous) });
        }
        self.tree.clone().expect("parsed above")
    }
}

/// A bracket on a line: it holds as long as the line's text and tokens do.
#[derive(Clone)]
pub struct LineBracket {
    range: Range<usize>,
    token: Arc<BracketToken>,
}

/// `NonPeekableTextBufferTokenizer.read` over one line: brackets only in `Other` tokens that may hold balanced
/// brackets, with neighbor tokens of equal metadata read as one.
pub fn line_brackets(text: &str, spans: &[Span], languages: &HashMap<String, LanguageBrackets>) -> Vec<LineBracket> {
    let mut found = Vec::new();
    let (mut position, mut index) = (0, 0);
    while index < spans.len() {
        let span = spans[index];
        while index + 1 < spans.len() && spans[index + 1].same_metadata(&span) {
            index += 1;
        }
        let end = spans[index].end.min(text.len());
        let mut bracket = None;
        if span.token_type == StandardTokenType::Other && span.balanced_brackets && position < end
            && let Some(brackets) = languages.get(span.language)
            && let Some(regex) = &brackets.regex
            && let Some((start, match_end)) = regex.find(&text[position..end])
        {
            bracket = brackets.token(&text[position + start..position + match_end]).map(|token| (position + start..position + match_end, token));
        }
        match bracket {
            // A token can hold more brackets, so read on from the bracket's end.
            Some((range, token)) => {
                position = range.end;
                found.push(LineBracket { range, token: token.clone() });
            }
            None => {
                index += 1;
                position = end;
            }
        }
    }
    found
}

/// A bracket node at `start` as the line and byte range it covers; brackets never span lines.
fn bracket_range(start: Length, node: &Node) -> BracketRange {
    (start.lines, start.columns..start.columns + node.length().columns)
}

/// `collectBrackets` with `onlyColorizedBrackets`, of the nodes that touch `range`, each with its start: a pair that is
/// not colorized (`<>` by default) adds no level and shows no brackets; an unclosed pair's opening bracket is invalid.
fn collect_brackets(node: &Node, start: Length, range: (Length, Length), level: isize, incomplete_parent: bool, found: &mut Vec<(Length, Bracket)>) {
    if level > 200 {
        return;
    }
    match node {
        Node::Text(_) => {}
        Node::Bracket { .. } => found.push((start, Bracket { range: bracket_range(start, node).1, level: level - 1, invalid: incomplete_parent })),
        Node::Unexpected { .. } => found.push((start, Bracket { range: bracket_range(start, node).1, level: level - 1, invalid: true })),
        Node::List { children, .. } => {
            let mut child_start = start;
            for child in children {
                let child_end = child_start + child.length();
                if child_start <= range.1 && child_end >= range.0 {
                    collect_brackets(child, child_start, range, level, false, found);
                }
                child_start = child_end;
            }
        }
        Node::Pair { open, close, .. } => {
            let colorize = match close.as_deref() {
                Some(Node::Bracket { token: close, .. }) => matches!(&**open, Node::Bracket { token: open, .. } if close.colorized_openings.has(open.key)),
                _ => true,
            };
            let child_level = if colorize { level + 1 } else { level };
            let mut child_start = start;
            for child in node.children() {
                let child_end = child_start + child.length();
                let is_bracket = matches!(**child, Node::Bracket { .. });
                if child_start <= range.1 && child_end >= range.0 && (colorize || !is_bracket || close.is_none()) {
                    collect_brackets(child, child_start, range, child_level, close.is_none(), found);
                }
                child_start = child_end;
            }
        }
    }
}

/// `collectBracketPairs`: the pairs that touch `range`, colorized or not, each before the pairs inside it.
fn collect_pairs(node: &Node, start: Length, range: (Length, Length), level: usize, pairs: &mut Vec<Pair>) {
    if level > 200 {
        return;
    }
    if let Node::Pair { length, open, child, close, .. } = node {
        let end = start + *length;
        let child_start = start + open.length();
        let close_start = child.as_ref().map_or(child_start, |child| child_start + child.length());
        pairs.push(Pair { open: bracket_range(start, open), close: close.as_ref().map(|close| bracket_range(close_start, close)), end: (end.lines, end.columns), level });
        if let Some(child) = child
            && child_start <= range.1
            && close_start >= range.0
        {
            collect_pairs(child, child_start, range, level + 1, pairs);
        }
        return;
    }
    let mut child_start = start;
    for child in node.children() {
        let child_end = child_start + child.length();
        if child_start <= range.1 && range.0 <= child_end {
            collect_pairs(child, child_start, range, level, pairs);
        }
        child_start = child_end;
    }
}

/// The brackets of the pairs, in document order: unexpected closing brackets are none.
fn collect_pair_brackets(node: &Node, start: Length, brackets: &mut Vec<PairBracket>) {
    if let Node::Bracket { token, .. } = node {
        brackets.push(PairBracket { range: bracket_range(start, node), opening: token.opening, key: token.id.clone() });
        return;
    }
    let mut child_start = start;
    for child in node.children() {
        collect_pair_brackets(child, child_start, brackets);
        child_start = child_start + child.length();
    }
}

/// `getFirstBracketAfter`: the first bracket of a pair that ends after `position`.
fn first_bracket_after(node: &Node, start: Length, position: Length) -> Option<BracketRange> {
    if let Node::Bracket { .. } = node {
        return Some(bracket_range(start, node));
    }
    let mut child_start = start;
    for child in node.children() {
        let child_end = child_start + child.length();
        if position < child_end
            && let Some(found) = first_bracket_after(child, child_start, position)
        {
            return Some(found);
        }
        child_start = child_end;
    }
    None
}

/// `editor.guides.bracketPairsHorizontal` as `HorizontalGuidesState`.
#[derive(Clone, Copy, PartialEq)]
pub enum HorizontalGuides {
    Disabled,
    EnabledForActive,
    Enabled,
}

/// `BracketGuideOptions`: `include_inactive` is `editor.guides.bracketPairs` true, where "active" draws only the
/// pair around the cursor.
pub struct BracketGuideOptions {
    pub include_inactive: bool,
    pub highlight_active: bool,
    pub horizontal: HorizontalGuides,
}

/// `IndentGuide` of a bracket pair: at `visible_column` (1-based), or with none right after char column `column`;
/// `horizontal` is a line along the top (`true`) or bottom of the line up to char column `end`. On a wrapped
/// line it shows only on the view lines after the one with char column `wrapped_after` and up to the one with
/// `wrapped_before_or_at` (`forWrappedLinesAfterColumn`, `forWrappedLinesBeforeOrAtColumn`).
#[derive(Clone, Debug, PartialEq)]
pub struct BracketGuide {
    pub visible_column: Option<usize>,
    pub column: usize,
    pub level: usize,
    pub active: bool,
    pub horizontal: Option<(bool, usize)>,
    pub wrapped_after: Option<usize>,
    pub wrapped_before_or_at: Option<usize>,
}

/// `getLinesBracketGuides` (guidesTextModelPart.ts): the guides of each line of `range` with the cursor at
/// (line, char column).
pub fn bracket_guides(pairs: &[Pair], lines: &[String], tab_size: usize, range: Range<usize>, cursor: Option<(usize, usize)>, options: &BracketGuideOptions) -> Vec<Vec<BracketGuide>> {
    let mut result = vec![Vec::new(); range.len()];
    let char_column = |(line, bytes): &BracketRange| lines[*line][..bytes.start].chars().count();
    let visible = |line: usize, column: usize| crate::editor::visible_column(&lines[line], column, tab_size) + 1;
    // `strictContainsPosition`, the innermost pair last.
    let active = cursor.and_then(|(line, column)| {
        let offset = lines[line].char_indices().nth(column).map_or(lines[line].len(), |(offset, _)| offset);
        pairs.iter().rev().find(|pair| (pair.open.0, pair.open.1.start) < (line, offset) && (line, offset) < pair.end)
    });
    for pair in pairs {
        let Some(close) = &pair.close else { continue };
        let (start_line, end_line) = (pair.open.0, close.0);
        if end_line < range.start || start_line >= range.end {
            continue;
        }
        let is_active = active.is_some_and(|active| std::ptr::eq(active, pair));
        if !is_active && !options.include_inactive {
            continue;
        }
        let guide = |visible_column, column, horizontal| BracketGuide {
            visible_column,
            column,
            level: pair.level,
            active: options.highlight_active && is_active,
            horizontal,
            wrapped_after: None,
            wrapped_before_or_at: None,
        };
        let (start_column, end_column) = (char_column(&pair.open), char_column(close));
        let horizontal = options.horizontal == HorizontalGuides::Enabled || (options.horizontal == HorizontalGuides::EnabledForActive && is_active);
        if start_line == end_line {
            if horizontal {
                let open_end = lines[start_line][..pair.open.1.end].chars().count();
                result[start_line - range.start].push(guide(None, open_end, Some((false, end_column))));
            }
            continue;
        }
        let (start_visible, end_visible) = (visible(start_line, start_column), visible(end_line, end_column));
        let guide_column = start_visible.min(end_visible).min(min_indentation(lines, tab_size, start_line + 1..end_line + 1).saturating_add(1));
        // Text before the closing bracket: the guide runs through its line and ends below it.
        let bottom = lines[end_line].chars().position(|c| c != ' ' && c != '\t').is_some_and(|first| first < end_column);
        for line in start_line.max(range.start)..end_line.min(range.end - 1) + bottom as usize {
            let wrapped_after = (line == start_line).then_some(start_column);
            let wrapped_before_or_at = (line == end_line).then_some(end_column);
            result[line - range.start].push(BracketGuide { wrapped_after, wrapped_before_or_at, ..guide(Some(guide_column), 0, None) });
        }
        if horizontal {
            if start_line >= range.start && start_visible > guide_column {
                result[start_line - range.start].push(guide(Some(guide_column), 0, Some((false, start_column))));
            }
            if end_line < range.end && end_visible > guide_column {
                result[end_line - range.start].push(guide(Some(guide_column), 0, Some((!bottom, end_column))));
            }
        }
    }
    for guides in &mut result {
        guides.sort_by_key(|guide| guide.visible_column);
    }
    result
}

/// `computeMinIndentation` of a pair's inside: the least indent (0-based visible column) of its non-blank lines.
fn min_indentation(lines: &[String], tab_size: usize, inside: Range<usize>) -> usize {
    let mut min = usize::MAX;
    for text in &lines[inside] {
        if let Some(first) = text.chars().position(|c| c != ' ' && c != '\t') {
            min = min.min(crate::editor::visible_column(text, first, tab_size));
        }
    }
    min
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;

    /// One `Other` token per line that may hold brackets, as `TokenizedDocument` in the upstream tests.
    fn brackets_of(text: &str, config: Value) -> Vec<(isize, Range<usize>, bool)> {
        let languages = HashMap::from([("test".to_string(), LanguageBrackets::new("test", &config))]);
        let style = Style { font_style: 0, foreground: 1, background: 2 };
        let span = Span { end: text.len(), language: "test", token_type: StandardTokenType::Other, balanced_brackets: true, style };
        DocumentBrackets::new(&[(text, vec![span])], &languages).line(0).into_iter().map(|b| (b.level, b.range, b.invalid)).collect()
    }

    fn colorized_config() -> Value {
        json!({ "brackets": [["<", ">"]], "colorizedBracketPairs": [["{", "}"], ["[", "]"], ["(", ")"]] })
    }

    /// brackets.test.ts "Basic".
    #[test]
    fn closing_brackets_close_every_opening_they_pair_with() {
        let config = json!({ "brackets": [
            ["{", "}"], ["[", "]"], ["(", ")"],
            ["begin", "end"], ["case", "endcase"], ["casez", "endcase"],
            ["\\left(", "\\right)"], ["\\left(", "\\right."], ["\\left.", "\\right)"],
            ["\\left[", "\\right]"], ["\\left[", "\\right."], ["\\left.", "\\right]"]
        ] });
        let brackets = LanguageBrackets::new("testMode1", &config);
        let token = |text: &str| {
            let token = brackets.token(text).unwrap();
            let strip = |id: &str| id.trim_start_matches("testMode1:::").to_string();
            (token.opening, strip(&token.id), token.ids.clone())
        };
        let ids = |texts: &[&str]| BracketIds::of(&texts.iter().map(|text| format!("testMode1:::{text}")).collect::<Vec<_>>());
        assert_eq!(token("begin"), (true, "begin".into(), ids(&["begin"])));
        assert_eq!(token("\\left."), (true, "\\left.".into(), ids(&["\\left."])));
        assert_eq!(token("end"), (false, "begin".into(), ids(&["begin"])));
        assert_eq!(token("endcase"), (false, "case".into(), ids(&["case", "casez"])));
        assert_eq!(token("\\right)"), (false, "\\left(".into(), ids(&["\\left(", "\\left."])));
        assert_eq!(token("\\right."), (false, "\\left(".into(), ids(&["\\left(", "\\left["])));
        assert_eq!(token("\\right]"), (false, "\\left[".into(), ids(&["\\left[", "\\left."])));
    }

    /// getBracketPairsInRange.test.ts "getBracketsInRange"; ranges are 0-based byte offsets.
    #[test]
    fn levels_follow_the_nesting() {
        let levels: Vec<isize> = brackets_of(" { [ ( [ [ (  ) ] ] ) ] } { } ", colorized_config()).into_iter().map(|(level, ..)| level).collect();
        assert_eq!(levels, [0, 1, 2, 3, 4, 5, 5, 4, 3, 2, 1, 0, 0, 0]);
    }

    /// "Test Error Brackets".
    #[test]
    fn unclosed_and_unexpected_brackets_are_invalid() {
        assert_eq!(brackets_of(" { () ] ", colorized_config()), [(0, 1..2, true), (1, 3..4, false), (1, 4..5, false), (0, 6..7, true)]);
    }

    /// "colorizedBracketsVSBrackets" with only the colorized brackets.
    #[test]
    fn pairs_that_are_not_colorized_add_no_level() {
        assert_eq!(
            brackets_of(" {} [<()>] <{>} ", colorized_config()),
            [(0, 1..2, false), (0, 2..3, false), (0, 4..5, false), (1, 6..7, false), (1, 7..8, false), (0, 9..10, false), (0, 12..13, true), (-1, 14..15, true)]
        );
    }

    #[test]
    fn matches_the_touched_bracket_else_the_enclosing_pair() {
        let text = "{ (abc), [def] }";
        let languages = HashMap::from([("test".to_string(), LanguageBrackets::new("test", &json!({ "brackets": [["{", "}"], ["[", "]"], ["(", ")"]] })))]);
        let style = Style { font_style: 0, foreground: 1, background: 2 };
        let span = Span { end: text.len(), language: "test", token_type: StandardTokenType::Other, balanced_brackets: true, style };
        let brackets = DocumentBrackets::new(&[(text, vec![span])], &languages);
        let ranges = |pair: Option<[BracketRange; 2]>| pair.map(|[open, close]| (open.1.clone(), close.1.clone()));
        assert_eq!(ranges(brackets.match_bracket(0, 2)), Some((2..3, 6..7)));
        // Right after ")": a bracket touches the position from either side.
        assert_eq!(ranges(brackets.match_bracket(0, 7)), Some((2..3, 6..7)));
        assert_eq!(ranges(brackets.match_bracket(0, 1)), Some((0..1, 15..16)));
        assert_eq!(ranges(brackets.match_bracket(0, 4)), None);
        assert_eq!(ranges(brackets.enclosing_brackets(0, 4)), Some((2..3, 6..7)));
        assert_eq!(ranges(brackets.enclosing_brackets(0, 8)), Some((0..1, 15..16)));
        assert_eq!(ranges(brackets.enclosing_brackets(0, 0)), None);
        // Between ")(" both brackets touch; the one starting later wins.
        let text = "()()";
        let span = Span { end: text.len(), ..span };
        let brackets = DocumentBrackets::new(&[(text, vec![span])], &languages);
        assert_eq!(ranges(brackets.match_bracket(0, 2)), Some((2..3, 3..4)));
    }

    #[test]
    fn a_bracket_pair_guide_runs_at_the_least_indent_of_its_lines() {
        let text = ["function f() {", "    if (a) {", "        b();", "    }", "}"].map(String::from);
        let languages = HashMap::from([("test".to_string(), LanguageBrackets::new("test", &json!({ "brackets": [["{", "}"], ["(", ")"]] })))]);
        let style = Style { font_style: 0, foreground: 1, background: 2 };
        let spans: Vec<_> = text.iter().map(|line| (line.as_str(), vec![Span { end: line.len(), language: "test", token_type: StandardTokenType::Other, balanced_brackets: true, style }])).collect();
        let pairs = DocumentBrackets::new(&spans, &languages).pairs_in_lines(0..5);
        let columns = |guides: Vec<Vec<BracketGuide>>| guides.into_iter().map(|line| line.into_iter().map(|guide| (guide.visible_column, guide.level, guide.active, guide.horizontal)).collect::<Vec<_>>()).collect::<Vec<_>>();
        let all = BracketGuideOptions { include_inactive: true, highlight_active: true, horizontal: HorizontalGuides::Disabled };
        let guides = columns(bracket_guides(&pairs, &text, 4, 0..5, None, &all));
        let vertical = |column, level| (Some(column), level, false, None);
        assert_eq!(guides, [vec![vertical(1, 0)], vec![vertical(1, 0), vertical(5, 1)], vec![vertical(1, 0), vertical(5, 1)], vec![vertical(1, 0)], vec![]]);
        // "active": only the innermost pair around the cursor, with its top line out to the opening bracket.
        let active = BracketGuideOptions { include_inactive: false, highlight_active: true, horizontal: HorizontalGuides::EnabledForActive };
        let guides = columns(bracket_guides(&pairs, &text, 4, 1..4, Some((2, 8)), &active));
        assert_eq!(guides, [vec![(Some(5), 1, true, None), (Some(5), 1, true, Some((false, 11)))], vec![(Some(5), 1, true, None)], vec![]]);
    }

    #[test]
    fn an_unclosed_pair_ends_where_its_parse_ended() {
        let text = ["{", "    (", "    x", "}"].map(String::from);
        let languages = HashMap::from([("test".to_string(), LanguageBrackets::new("test", &json!({ "brackets": [["{", "}"], ["(", ")"]] })))]);
        let style = Style { font_style: 0, foreground: 1, background: 2 };
        let spans: Vec<_> = text.iter().map(|line| (line.as_str(), vec![Span { end: line.len(), language: "test", token_type: StandardTokenType::Other, balanced_brackets: true, style }])).collect();
        let pairs = DocumentBrackets::new(&spans, &languages).pairs_in_lines(0..4);
        assert_eq!(pairs.iter().map(|pair| pair.end).collect::<Vec<_>>(), [(3, 1), (3, 0)]);
        // The `}` closes `{` and ends the unclosed `(` before it, so the cursor there is in `{` only.
        let active = BracketGuideOptions { include_inactive: false, highlight_active: true, horizontal: HorizontalGuides::Disabled };
        let guides = bracket_guides(&pairs, &text, 4, 0..4, Some((3, 0)), &active);
        assert!(guides.iter().flatten().all(|guide| guide.active && guide.level == 0) && guides.iter().flatten().count() > 0, "{guides:?}");
    }

    #[test]
    fn word_brackets_need_word_boundaries() {
        let config = json!({ "brackets": [["begin", "end"]] });
        assert_eq!(brackets_of("begin x beginning end", config), [(0, 0..5, false), (0, 18..21, false)]);
    }

    /// `createTextModelWithColorizedBracketPairs` of getBracketPairsInRange.test.ts over one line.
    fn colorized_document(text: &str) -> DocumentBrackets {
        let languages = HashMap::from([("test".to_string(), LanguageBrackets::new("test", &colorized_config()))]);
        let style = Style { font_style: 0, foreground: 1, background: 2 };
        let span = Span { end: text.len(), language: "test", token_type: StandardTokenType::Other, balanced_brackets: true, style };
        DocumentBrackets::new(&[(text, vec![span])], &languages)
    }

    /// Each pair as (level, open, close) byte ranges on line 0.
    fn pairs_between(text: &str, from: usize, to: usize) -> Vec<(usize, Range<usize>, Option<Range<usize>>)> {
        colorized_document(text).pairs_in((0, from), (0, to)).into_iter().map(|pair| (pair.level, pair.open.1, pair.close.map(|close| close.1))).collect()
    }

    /// getBracketPairsInRange.test.ts "Basic 1", "Basic 2", "Basic Empty" and "Basic All", the markers at byte offsets.
    #[test]
    fn pairs_in_range_are_the_pairs_that_touch_it() {
        let text = "{ ( []  ) [  { } ] () } []";
        assert_eq!(pairs_between(text, 7, 12), [(0, 0..1, Some(22..23)), (1, 2..3, Some(8..9)), (1, 10..11, Some(17..18))]);
        assert_eq!(pairs_between(text, 7, 8), [(0, 0..1, Some(22..23)), (1, 2..3, Some(8..9))]);
        assert_eq!(pairs_between("  { ( [] ) [  { } ] () } []", 0, 1), []);
        let all = pairs_between(" { ( [] ) [  { } ] () } [] ", 0, 27);
        let expected = [(0, 1..2, 22..23), (1, 3..4, 8..9), (2, 5..6, 6..7), (1, 10..11, 17..18), (2, 13..14, 15..16), (1, 19..20, 20..21), (0, 24..25, 25..26)];
        assert_eq!(all, expected.map(|(level, open, close)| (level, open, Some(close))));
    }

    /// A tree of brackets over `lines`, one `Other` token per line, as `TokenStore` keeps it.
    fn cached_document(cache: &mut BracketCache, lines: &[String], languages: &HashMap<String, LanguageBrackets>) -> DocumentBrackets {
        let style = Style { font_style: 0, foreground: 1, background: 2 };
        cache.document(lines, |index| {
            let span = Span { end: lines[index].len(), language: "test", token_type: StandardTokenType::Other, balanced_brackets: true, style };
            line_brackets(&lines[index], &[span], languages)
        })
    }

    fn first_pair(node: &Arc<Node>) -> Option<&Arc<Node>> {
        match &**node {
            Node::Pair { .. } => Some(node),
            _ => node.children().find_map(first_pair),
        }
    }

    /// `parseDocument` with the tree before an edit reuses the pairs the edit left.
    #[test]
    fn an_edit_reuses_the_pairs_before_it() {
        let languages = HashMap::from([("test".to_string(), LanguageBrackets::new("test", &colorized_config()))]);
        let mut lines: Vec<String> = ["{ ( [] ) }", "x", "(y)"].map(String::from).into();
        let mut cache = BracketCache::new(lines.len());
        let before = cached_document(&mut cache, &lines, &languages);
        lines[2] = "(z))".to_string();
        cache.accept_edit(2, 2, 1);
        let after = cached_document(&mut cache, &lines, &languages);
        assert!(Arc::ptr_eq(first_pair(&before.root).unwrap(), first_pair(&after.root).unwrap()));
        assert_eq!(after.line(2).len(), 3);
    }

    /// The tree after random line edits holds the brackets and pairs of a tree parsed from scratch.
    #[test]
    fn edits_leave_the_tree_a_fresh_parse_builds() {
        let languages = HashMap::from([("test".to_string(), LanguageBrackets::new("test", &colorized_config()))]);
        let mut seed = 0x2545_f491_4f6c_dd1du64;
        let mut next = |bound: usize| {
            seed ^= seed << 13;
            seed ^= seed >> 7;
            seed ^= seed << 17;
            (seed % bound as u64) as usize
        };
        let alphabet = ['{', '}', '(', ')', '[', ']', '<', '>', ' ', 'a'];
        let random_line = |next: &mut dyn FnMut(usize) -> usize| (0..next(12)).map(|_| alphabet[next(alphabet.len())]).collect::<String>();
        let mut lines: Vec<String> = (0..40).map(|_| random_line(&mut next)).collect();
        let mut cache = BracketCache::new(lines.len());
        for _ in 0..300 {
            let start = next(lines.len());
            let end = start + next((lines.len() - start).min(3));
            let new_lines: Vec<String> = (0..1 + next(3)).map(|_| random_line(&mut next)).collect();
            cache.accept_edit(start, end, new_lines.len());
            lines.splice(start..=end, new_lines);
            let edited = cached_document(&mut cache, &lines, &languages);
            let style = Style { font_style: 0, foreground: 1, background: 2 };
            let spans: Vec<_> = lines.iter().map(|text| (text.as_str(), vec![Span { end: text.len(), language: "test", token_type: StandardTokenType::Other, balanced_brackets: true, style }])).collect();
            let fresh = DocumentBrackets::new(&spans, &languages);
            let all = 0..lines.len();
            let pairs = |document: &DocumentBrackets| document.pairs_in_lines(all.clone()).into_iter().map(|pair| (pair.open, pair.close, pair.end, pair.level)).collect::<Vec<_>>();
            assert_eq!(pairs(&edited), pairs(&fresh), "{lines:?}");
            for line in all.clone() {
                assert_eq!(edited.line(line), fresh.line(line), "line {line} of {lines:?}");
            }
        }
    }
}