Skip to content

Visual Studio Code, rebuilt in Rust

Rust
58.6 KB
Raw Blame
//! Token colors in the editor: the theme's `tokenColors` as `ColorThemeData.tokenColors` hands them
//! to vscode-textmate, and the text model's TextMate tokens (textModelTokens.ts), kept per line.

use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::time::{Duration, Instant};
use std::ops::Range;

use gpui::{FontStyle, FontWeight, HighlightStyle, Hsla, Rgba, StrikethroughStyle, UnderlineStyle, px};
use serde_json::{Map, Value, json};
use textmate::{Grammar, State, Token};

use crate::brackets::{BracketCache, BracketGuide, BracketGuideOptions, BracketRange, DocumentBrackets, Span, line_brackets};
use crate::languages::Languages;
use crate::theme::{Theme, ThemeKind};

mod invalid_lines;
use invalid_lines::InvalidLines;

/// How many untrusted lines pairing brackets after an edit tokenizes first (about 2 ms of TypeScript in a release
/// build); the background tokenizer does the rest.
const BRACKET_TOKENIZE_LINES: usize = 20;

/// `editor.maxTokenizationLineLength`: a longer line gets no tokens and passes the state through.
const MAX_TOKENIZATION_LINE_LENGTH: usize = 20_000;

/// `ColorThemeData.tokenColors`: the editor colors as the default rule, then the theme's rules, then
/// the `token.*-token` defaults unless the theme sets `token.info-token`.
pub fn token_theme(theme: &Theme, rules: &[Value]) -> textmate::Theme {
    let editor_hex = |key: &str| css_hex(theme.color(key).expect("editor colors have registry defaults"));
    let mut result = vec![json!({ "settings": { "foreground": editor_hex("editor.foreground"), "background": editor_hex("editor.background") } })];
    let has_default_tokens = rules.iter().any(|rule| rule["scope"] == "token.info-token" && rule["settings"].is_object());
    let defaults = if has_default_tokens { Vec::new() } else { default_token_colors(theme.kind) };
    for rule in rules.iter().chain(&defaults) {
        // `rule.scope && rule.settings`: an empty string scope is falsy in JS, an empty array is not.
        if rule["scope"].is_null() || rule["scope"] == "" || !rule["settings"].is_object() {
            continue;
        }
        let settings = &rule["settings"];
        let mut normalized = Map::new();
        for key in ["foreground", "background"] {
            if let Some(color) = settings[key].as_str().and_then(normalize_color) {
                normalized.insert(key.into(), color.into());
            }
        }
        if !settings["fontStyle"].is_null() {
            normalized.insert("fontStyle".into(), settings["fontStyle"].clone());
        }
        result.push(json!({ "scope": rule["scope"], "settings": normalized }));
    }
    textmate::Theme::new(&result)
}

fn default_token_colors(kind: ThemeKind) -> Vec<Value> {
    let (info, warn, error, debug) = match kind {
        ThemeKind::Light | ThemeKind::HighContrastLight => ("#316bcd", "#cd9731", "#cd3131", "#800080"),
        ThemeKind::Dark => ("#6796e6", "#cd9731", "#f44747", "#b267e6"),
        ThemeKind::HighContrastDark => ("#6796e6", "#008000", "#FF0000", "#b267e6"),
    };
    [("token.info-token", info), ("token.warn-token", warn), ("token.error-token", error), ("token.debug-token", debug)]
        .into_iter()
        .map(|(scope, foreground)| json!({ "scope": scope, "settings": { "foreground": foreground } }))
        .collect()
}

/// `Color.Format.CSS.formatHexA(color, true)` in upper case, as `normalizeColor` leaves it.
fn css_hex(color: Rgba) -> String {
    let byte = |v: f32| (v * 255.).round() as u8;
    let hex = format!("#{:02X}{:02X}{:02X}", byte(color.r), byte(color.g), byte(color.b));
    if color.a < 1. { format!("{hex}{:02X}", byte(color.a)) } else { hex }
}

/// `normalizeColor` (colorThemeData.ts): `#RGB`, `#RGBA`, `#RRGGBB` or `#RRGGBBAA` in upper case,
/// short forms doubled, an opaque alpha dropped; anything else is no color.
fn normalize_color(color: &str) -> Option<String> {
    let digits = color.strip_prefix('#')?;
    if ![3, 4, 6, 8].contains(&digits.len()) || !digits.chars().all(|c| c.is_ascii_hexdigit()) {
        return None;
    }
    let mut result: String = if digits.len() <= 4 { digits.chars().flat_map(|c| [c, c]).collect() } else { digits.to_string() };
    result.make_ascii_uppercase();
    if result.len() == 8 && result.ends_with("FF") {
        result.truncate(6);
    }
    Some(format!("#{result}"))
}

/// The TextMate tokens of a document's lines, tokenized as far as a line is read, and the colorized brackets
/// of the whole document.
#[derive(Default)]
pub struct Tokenization {
    grammar: Option<Rc<Grammar>>,
    /// Filled while drawing, so behind a RefCell.
    lines: RefCell<TokenStore>,
    /// Dropped whenever a line's tokens change (bracketPairsTree.ts `handleDidChangeTokens`).
    brackets: RefCell<Option<Rc<DocumentBrackets>>>,
    /// `DefaultBackgroundTokenizer._isScheduled`.
    background_scheduled: Cell<bool>,
}

/// textModelTokens.ts `TrackingTokenizationStateStore` with each line's tokens: a line's tokens stay, stale, after an
/// edit until it is tokenized again, and an end state equal to the old one ends the retokenizing.
#[derive(Default)]
struct TokenStore {
    tokens: Vec<Vec<Token>>,
    end_states: Vec<Option<State>>,
    invalid: InvalidLines,
    /// The brackets under the drawing theme, and under the empty theme `pairs` reads.
    brackets: BracketCache,
    plain_brackets: BracketCache,
    /// abstractSyntaxTokenBackend.ts `AttachedViewHandler._computedLineRanges`: the lines in view last tokenized, and
    /// whether their tokens were guessed.
    viewport: Option<(usize, usize, bool)>,
}

impl TokenStore {
    /// A store of `line_count` lines, none tokenized.
    fn reset(&mut self, line_count: usize) {
        self.tokens = (0..line_count).map(|_| Vec::new()).collect();
        self.end_states = vec![None; line_count];
        self.invalid = InvalidLines::default();
        self.invalid.add_range(0..line_count);
        self.brackets = BracketCache::new(line_count);
        self.plain_brackets = BracketCache::new(line_count);
        self.viewport = None;
    }

    /// `setEndState`: an end state that changed makes the next line's end state untrusted.
    fn set_end_state(&mut self, line: usize, state: State) {
        self.invalid.delete(line);
        let changed = self.end_states[line].as_ref().is_none_or(|old| !old.equals(&state));
        self.end_states[line] = Some(state);
        if changed && line + 1 < self.end_states.len() {
            self.invalid.add_range(line + 1..line + 2);
        }
    }
}

impl Tokenization {
    pub fn new(grammar: Option<Rc<Grammar>>) -> Self {
        Tokenization { grammar, lines: RefCell::default(), brackets: RefCell::default(), background_scheduled: Cell::new(false) }
    }

    /// The token styles of line `index` over its tab-expanded text, brackets in their pair colors
    /// (`editor.bracketPairColorization.enabled` defaults on); none without a grammar.
    pub fn highlights(&self, theme: &Theme, languages: &Languages, lines: &[String], index: usize, tab_size: usize) -> Vec<(Range<usize>, HighlightStyle)> {
        if self.grammar.is_none() {
            return Vec::new();
        }
        let brackets = self.brackets(theme, languages, lines);
        self.tokenize_for_view(lines, index);
        let tokenized = self.lines.borrow();
        let highlights = token_highlights(&theme.tokens, &lines[index], &tokenized.tokens[index], tab_size);
        let expanded_offset = expanded_offsets(&lines[index], tab_size);
        let colors = bracket_colors(theme);
        let unexpected = theme.color("editorBracketHighlight.unexpectedBracket.foreground").map(Hsla::from);
        let mut colored = Vec::new();
        for bracket in brackets.line(index) {
            // An undefined color leaves the CSS rule invalid, so the token color stays.
            let color = if bracket.invalid { unexpected } else { colors.get((bracket.level % 30) as usize % colors.len().max(1)).copied() };
            if let Some(color) = color {
                colored.push((expanded_offset[bracket.range.start]..expanded_offset[bracket.range.end], color));
            }
        }
        overlay_colors(highlights, &colored)
    }

    /// The token styles of line `index` without bracket pair colors, as `tokenizeToString` renders code blocks.
    pub fn token_styles(&self, theme: &Theme, lines: &[String], index: usize, tab_size: usize) -> Vec<(Range<usize>, HighlightStyle)> {
        if self.grammar.is_none() {
            return Vec::new();
        }
        self.tokenize_to(lines, index);
        token_highlights(&theme.tokens, &lines[index], &self.lines.borrow().tokens[index], tab_size)
    }

    /// The minimap's view of line `index` (`getMinimapLinesRenderingData`): each token's end byte offset with
    /// its foreground. Bracket pair colors are decorations upstream, so the minimap does not show them. `colors` is
    /// `theme.tokens.color_map()` as `minimap_colors` parses it.
    pub fn minimap_runs(&self, theme: &Theme, colors: &[[u8; 3]], lines: &[String], index: usize) -> Vec<(usize, [u8; 3])> {
        let text = &lines[index];
        let default_run = vec![(text.len(), colors[1])];
        if self.grammar.is_none() {
            return default_run;
        }
        self.tokenize_for_view(lines, index);
        let tokenized = self.lines.borrow();
        let tokens = &tokenized.tokens[index];
        if tokens.is_empty() {
            return default_run;
        }
        tokens.iter().map(|token| (token.end.min(text.len()), colors[theme.tokens.style(&token.scopes).foreground])).collect()
    }

    /// The token color map as the RGB bytes `minimap_runs` takes; index 0, "not set", is black.
    pub fn minimap_colors(theme: &Theme) -> Vec<[u8; 3]> {
        let color_map = theme.tokens.color_map();
        let mut colors = vec![[0; 3]];
        for hex in &color_map[1..] {
            let color = Rgba::try_from(hex.as_str()).expect("the token color map holds hex colors");
            colors.push([color.r, color.g, color.b].map(|channel| (channel * 255.).round() as u8));
        }
        colors
    }

    /// The byte offsets where `renderViewLine` starts a span on line `index`: a token whose style differs from the
    /// one before it (tokens of equal metadata are one), and each colorized bracket's start and end.
    pub fn span_starts(&self, theme: &Theme, languages: &Languages, lines: &[String], index: usize) -> Vec<usize> {
        let mut starts = vec![0];
        if self.grammar.is_none() {
            return starts;
        }
        let brackets = self.brackets(theme, languages, lines);
        self.tokenize_for_view(lines, index);
        let tokenized = self.lines.borrow();
        let mut previous = None;
        let mut start = 0;
        for token in &tokenized.tokens[index] {
            let style = (theme.tokens.style(&token.scopes), token.token_type);
            if previous.is_some_and(|previous| previous != style) {
                starts.push(start);
            }
            previous = Some(style);
            start = token.end;
        }
        for bracket in brackets.line(index) {
            starts.extend([bracket.range.start, bracket.range.end]);
        }
        starts.retain(|&start| start < lines[index].len() || start == 0);
        starts.sort_unstable();
        starts.dedup();
        starts
    }

    /// The tokens of line `index` for the HTML copy, in chars, merged where their metadata is equal as
    /// vscode-textmate's `tokenizeLine2` gives them; one default token without a grammar.
    pub fn html_tokens(&self, theme: &Theme, lines: &[String], index: usize) -> Vec<crate::editor::clipboard::HtmlToken> {
        use crate::editor::clipboard::HtmlToken;
        let text = &lines[index];
        let default_token = vec![HtmlToken { end: text.chars().count(), foreground: 1, font_style: 0 }];
        if self.grammar.is_none() {
            return default_token;
        }
        self.tokenize_to(lines, index);
        let tokenized = self.lines.borrow();
        let mut tokens: Vec<(HtmlToken, _)> = Vec::new();
        for token in &tokenized.tokens[index] {
            let style = theme.tokens.style(&token.scopes);
            let metadata = (style, token.token_type, token.scopes.language.clone());
            let end = text[..token.end.min(text.len())].chars().count();
            match tokens.last_mut() {
                Some((last, last_metadata)) if *last_metadata == metadata => last.end = end,
                _ => tokens.push((HtmlToken { end, foreground: style.foreground, font_style: style.font_style.max(0) }, metadata)),
            }
        }
        if tokens.is_empty() {
            return default_token;
        }
        tokens.into_iter().map(|(token, _)| token).collect()
    }

    /// `getLanguageId` of the token at byte `offset` of line `index`: an embedded language, else none.
    pub fn language_at(&self, lines: &[String], index: usize, offset: usize) -> Option<std::rc::Rc<str>> {
        self.grammar.as_ref()?;
        self.tokenize_to(lines, index);
        self.stored_language_at(index, offset)
    }

    /// `tokenizeIfCheap` then `getLanguageIdAtPosition`: a line past the cheap one is read with the tokens it has.
    pub fn language_at_if_cheap(&self, lines: &[String], index: usize, offset: usize) -> Option<std::rc::Rc<str>> {
        self.grammar.as_ref()?;
        if self.is_cheap_to_tokenize(lines, index) {
            self.tokenize_to(lines, index);
        }
        self.stored_language_at(index, offset)
    }

    fn stored_language_at(&self, index: usize, offset: usize) -> Option<std::rc::Rc<str>> {
        let tokenized = self.lines.borrow();
        let tokens = &tokenized.tokens[index];
        tokens.iter().find(|token| token.end > offset).or(tokens.last()).and_then(|token| token.scopes.language.clone())
    }

    /// textModelTokens.ts `hasAccurateTokensForLine`: line `index` is before the first one with an untrusted end state.
    pub fn has_accurate_tokens_for_line(&self, lines: &[String], index: usize) -> bool {
        self.first_untrusted_line(lines).is_none_or(|first_untrusted| index < first_untrusted)
    }

    /// `getFirstInvalidEndStateLineNumber`: the first line waiting for its tokens, none once every line has them.
    pub fn first_untrusted_line(&self, lines: &[String]) -> Option<usize> {
        self.grammar.as_ref()?;
        self.synced(lines).invalid.min()
    }

    /// `getStandardTokenType` of the token at byte `offset` of line `index` (`findTokenIndexAtOffset`).
    pub fn token_type_at(&self, lines: &[String], index: usize, offset: usize) -> textmate::StandardTokenType {
        if self.grammar.is_some() {
            self.tokenize_to(lines, index);
        }
        self.stored_token_type_at(lines, index, offset)
    }

    /// `getLineTokens(...).getStandardTokenType`: the type at byte `offset` from the tokens line `index` has, which a
    /// line not tokenized yet has none of.
    pub fn stored_token_type_at(&self, lines: &[String], index: usize, offset: usize) -> textmate::StandardTokenType {
        if self.grammar.is_none() {
            return textmate::StandardTokenType::Other;
        }
        let tokenized = self.synced(lines);
        let tokens = &tokenized.tokens[index];
        tokens.iter().find(|token| token.end > offset).or(tokens.last()).map_or(textmate::StandardTokenType::Other, |token| token.token_type)
    }

    /// `getTokenTypeIfInsertingCharacter`: the standard type at byte `offset` of line `index` once `ch` is inserted there,
    /// the line tokenized again from its start state.
    pub fn token_type_if_inserting(&self, lines: &[String], index: usize, offset: usize, ch: char) -> textmate::StandardTokenType {
        let Some(grammar) = self.grammar.as_ref() else { return textmate::StandardTokenType::Other };
        self.tokenize_to(lines, index);
        let store = self.lines.borrow();
        let previous = index.checked_sub(1).and_then(|line| store.end_states[line].as_ref());
        let mut text = lines[index].clone();
        text.insert(offset, ch);
        let Ok((tokens, _)) = grammar.tokenize_line(&text, previous) else { return textmate::StandardTokenType::Other };
        tokens.iter().find(|token| token.end > offset).or(tokens.last()).map_or(textmate::StandardTokenType::Other, |token| token.token_type)
    }

    /// inspectEditorTokens.ts `_getTokensAtPosition`: the token at byte `offset` of line `index` (the last one starting
    /// at or before it, else the first) from a fresh tokenization of the lines up to it, with no line length limit:
    /// its byte range, scopes and standard type; none without a grammar or tokens.
    pub fn token_at(&self, lines: &[String], index: usize, offset: usize) -> Option<(Range<usize>, std::rc::Rc<textmate::ScopeStack>, textmate::StandardTokenType)> {
        let grammar = self.grammar.as_ref()?;
        let mut state = None;
        for line in &lines[..index] {
            if let Ok((_, next)) = grammar.tokenize_line(line, state.as_ref()) {
                state = Some(next);
            }
        }
        let (tokens, _) = grammar.tokenize_line(&lines[index], state.as_ref()).ok()?;
        let token = tokens.iter().rev().find(|token| token.start <= offset).or(tokens.first())?;
        Some((token.start..token.end.min(lines[index].len()), token.scopes.clone(), token.token_type))
    }

    /// The tokens of line `index` as (byte end, standard type, embedded language), or one `Other` token over
    /// the line without a grammar or tokens.
    pub fn line_tokens(&self, lines: &[String], index: usize) -> Vec<(usize, textmate::StandardTokenType, Option<std::rc::Rc<str>>)> {
        let len = lines[index].len();
        if self.grammar.is_none() {
            return vec![(len, textmate::StandardTokenType::Other, None)];
        }
        self.tokenize_to(lines, index);
        let tokens: Vec<_> = self.lines.borrow().tokens[index].iter().map(|token| (token.end.min(len), token.token_type, token.scopes.language.clone())).collect();
        if tokens.is_empty() {
            return vec![(len, textmate::StandardTokenType::Other, None)];
        }
        tokens
    }

    /// `findMatchingBracketUp`: the line of the opening bracket that `close` closes in the innermost pair
    /// around (line, byte), its closing bracket typed or not.
    pub fn matching_bracket_up(&self, languages: &Languages, lines: &[String], language: &str, close: &str, line: usize, offset: usize) -> Option<usize> {
        let config = languages.brackets.get(language)?;
        let brackets = self.pairs(languages, lines, language);
        let pairs = brackets.pairs_in((line, offset), (line, offset));
        let pair = pairs.iter().rev().find(|pair| {
            let (open_line, open_range) = &pair.open;
            let starts_before = (*open_line, open_range.start) <= (line, offset);
            let ends_after = pair.end >= (line, offset);
            starts_before && ends_after && config.closes(close, &lines[*open_line][open_range.clone()])
        })?;
        Some(pair.open.0)
    }

    /// The bracket pairs of the document in `language`, also without a grammar.
    pub fn pairs(&self, languages: &Languages, lines: &[String], language: &str) -> DocumentBrackets {
        self.document_brackets(&textmate::Theme::new(&[]), languages, lines, language, true)
    }

    /// bracketPairsImpl.ts `hasUnmatchedClosingBracketAfter` at (line, byte), false until every line has its tokens.
    pub fn has_unmatched_closing_bracket_after(&self, languages: &Languages, lines: &[String], language: &str, open: &str, line: usize, offset: usize) -> bool {
        if self.grammar.is_some() && self.synced(lines).invalid.min().is_some() {
            return false;
        }
        let Some(config) = languages.brackets.get(language) else { return false };
        self.pairs(languages, lines, language).has_unmatched_closing_after(config, open, line, offset)
    }

    /// `bracket_guides` of lines `range` over the pairs the brackets were colored with, or `pairs` without a grammar.
    #[allow(clippy::too_many_arguments)]
    pub fn bracket_guides(&self, theme: &Theme, languages: &Languages, lines: &[String], language: &str, tab_size: usize, range: Range<usize>, cursor: Option<(usize, usize)>, options: &BracketGuideOptions) -> Vec<Vec<BracketGuide>> {
        if self.grammar.is_some() {
            return crate::brackets::bracket_guides(&self.brackets(theme, languages, lines).pairs_in_lines(range.clone()), lines, tab_size, range, cursor, options);
        }
        crate::brackets::bracket_guides(&self.pairs(languages, lines, language).pairs_in_lines(range.clone()), lines, tab_size, range, cursor, options)
    }

    /// `BracketMatchingController` with `editor.matchBrackets` "always": the pair whose bracket touches
    /// the cursor (line, char column), shown in the overview ruler, else the pair around it, not shown there.
    pub fn bracket_match(&self, theme: &Theme, languages: &Languages, lines: &[String], cursor: (usize, usize)) -> Option<([BracketRange; 2], bool)> {
        self.grammar.as_ref()?;
        let brackets = self.brackets(theme, languages, lines);
        let (line, column) = cursor;
        let offset = lines[line].char_indices().nth(column).map_or(lines[line].len(), |(offset, _)| offset);
        match brackets.match_bracket(line, offset) {
            Some(pair) => Some((pair, true)),
            None => brackets.enclosing_brackets(line, offset).map(|pair| (pair, false)),
        }
    }

    /// `acceptChange` after an edit that replaced lines `start..=end` by `new_line_count` lines: their end states
    /// are untrusted, the last one kept to compare with; the first line keeps its stale tokens, the others have none
    /// until tokenized. The bracket tree is parsed again on its next read, reusing the nodes the edit left.
    pub fn accept_edit(&mut self, start: usize, end: usize, new_line_count: usize) {
        *self.brackets.get_mut() = None;
        let store = self.lines.get_mut();
        if store.tokens.is_empty() {
            return;
        }
        store.viewport = None;
        store.tokens.splice(start + 1..=end, (1..new_line_count).map(|_| Vec::new()));
        store.end_states.splice(start..end, (1..new_line_count).map(|_| None));
        store.invalid.add_range_and_resize(start..end + 1, new_line_count);
        store.brackets.accept_edit(start, end, new_line_count);
        store.plain_brackets.accept_edit(start, end, new_line_count);
    }

    /// tokenization.ts `ForceRetokenizeAction`: `resetTokenization`, then `forceTokenization` of every line.
    pub fn force_retokenize(&mut self, lines: &[String]) {
        *self.brackets.get_mut() = None;
        self.lines.get_mut().reset(lines.len());
        if self.grammar.is_some() && !lines.is_empty() {
            self.tokenize_to(lines, lines.len() - 1);
        }
    }

    /// textModelTokens.ts `isCheapToTokenize`: line `index` is tokenized, or the first one not yet and shorter
    /// than `CHEAP_TOKENIZATION_LENGTH_LIMIT` (2048).
    pub fn is_cheap_to_tokenize(&self, lines: &[String], index: usize) -> bool {
        if self.grammar.is_none() {
            return true;
        }
        let first_invalid = self.synced(lines).invalid.min().unwrap_or(usize::MAX);
        index < first_invalid || (index == first_invalid && lines[index].encode_utf16().count() < 2048)
    }

    /// The bracket pairs hold token styles of the theme they were paired under.
    pub fn theme_changed(&mut self) {
        *self.brackets.get_mut() = None;
        let store = self.lines.get_mut();
        store.brackets = BracketCache::new(store.tokens.len());
    }

    fn brackets(&self, theme: &Theme, languages: &Languages, lines: &[String]) -> Rc<DocumentBrackets> {
        if let Some(brackets) = &*self.brackets.borrow() {
            return brackets.clone();
        }
        let brackets = Rc::new(self.document_brackets(&theme.tokens, languages, lines, "", false));
        *self.brackets.borrow_mut() = Some(brackets.clone());
        brackets
    }

    /// The bracket pairs over the tokens as they are, as bracketPairsTree.ts reads the token store while the background
    /// tokenizer runs: a line not tokenized yet holds no brackets. The lines an edit left untrusted are tokenized first,
    /// `BRACKET_TOKENIZE_LINES` at most, so the edited line's brackets count. Only lines whose text or tokens changed
    /// are read again; `plain` picks the brackets under the empty theme. Without a grammar each line is one `Other`
    /// token in `language` (`nullTokenize`).
    fn document_brackets(&self, theme: &textmate::Theme, languages: &Languages, lines: &[String], language: &str, plain: bool) -> DocumentBrackets {
        if self.grammar.is_some() {
            self.tokenize_for(lines, Duration::MAX, BRACKET_TOKENIZE_LINES);
        }
        let mut store = self.synced(lines);
        let TokenStore { tokens, brackets, plain_brackets, .. } = &mut *store;
        let cache = if plain { plain_brackets } else { brackets };
        cache.document(lines, |index| {
            let spans: Vec<_> = match self.grammar {
                Some(_) => tokens[index]
                    .iter()
                    .map(|token| Span {
                        end: token.end,
                        language: token.scopes.language.as_deref().unwrap_or_default(),
                        token_type: token.token_type,
                        balanced_brackets: token.balanced_brackets,
                        style: theme.style(&token.scopes),
                    })
                    .collect(),
                None => {
                    let style = textmate::Style { font_style: 0, foreground: 0, background: 0 };
                    vec![Span { end: lines[index].len(), language, token_type: textmate::StandardTokenType::Other, balanced_brackets: true, style }]
                }
            };
            line_brackets(&lines[index], &spans, &languages.brackets)
        })
    }

    /// tokenizerSyntaxTokenBackend.ts `refreshRange` for lines `first..=last` in view, once per range
    /// (`AttachedViewHandler.update`).
    pub fn tokenize_viewport(&self, lines: &[String], first: usize, last: usize) {
        if self.grammar.is_none() || lines.is_empty() {
            return;
        }
        let last = last.min(lines.len() - 1);
        if self.synced(lines).viewport.is_some_and(|(computed_first, computed_last, _)| (computed_first, computed_last) == (first, last)) {
            return;
        }
        let guessed = self.tokenize_heuristically(lines, first, last);
        self.lines.borrow_mut().viewport = Some((first, last, guessed));
    }

    /// textModelTokens.ts `tokenizeHeuristically`: lines in view past the first untrusted one get tokens from a
    /// guessed start state, and the background tokenizes them again (`requestTokens`); true then.
    fn tokenize_heuristically(&self, lines: &[String], first: usize, last: usize) -> bool {
        let first_invalid = self.synced(lines).invalid.min().unwrap_or(usize::MAX);
        if last <= first_invalid {
            return false;
        }
        if first <= first_invalid {
            self.tokenize_to(lines, last);
            return false;
        }
        let grammar = self.grammar.as_ref().expect("checked by the caller");
        let mut store = self.synced(lines);
        let mut state = guess_start_state(grammar, &store, lines, first);
        for line in first..=last {
            let (tokens, end_state) = tokenize_text(grammar, lines, line, state.as_ref());
            store.tokens[line] = tokens;
            store.brackets.lines[line] = None;
            store.plain_brackets.lines[line] = None;
            *self.brackets.borrow_mut() = None;
            state = Some(end_state);
        }
        store.invalid.add_range(first..last + 1);
        true
    }

    /// The view's reads: tokenizerSyntaxTokenBackend.ts `getLineTokens` takes the tokens as they are while the lines
    /// in view hold guessed ones, else the lines up to `index` are tokenized.
    fn tokenize_for_view(&self, lines: &[String], index: usize) {
        if self.synced(lines).viewport.is_some_and(|(_, _, guessed)| guessed) {
            return;
        }
        self.tokenize_to(lines, index);
    }

    /// `updateTokensUntilLine`: tokenizes each line with an untrusted end state up to line `index`.
    fn tokenize_to(&self, lines: &[String], index: usize) {
        let mut store = self.synced(lines);
        while let Some(line) = store.invalid.min().filter(|&line| line <= index) {
            self.tokenize_line(&mut store, lines, line);
        }
    }

    /// `DefaultBackgroundTokenizer._beginBackgroundTokenization`: true when lines wait for tokens and no background
    /// tokenization is scheduled yet, which the caller then schedules.
    pub fn begin_background_tokenization(&self, lines: &[String]) -> bool {
        if self.grammar.is_none() || self.background_scheduled.get() || self.synced(lines).invalid.is_empty() {
            return false;
        }
        self.background_scheduled.set(true);
        true
    }

    /// `_backgroundTokenizeForAtLeast1ms`: tokenizes lines with an untrusted end state, at least one, until `budget`
    /// has passed; true while some are left.
    pub fn tokenize_in_background(&mut self, lines: &[String], budget: Duration) -> bool {
        if self.grammar.is_some() {
            self.tokenize_for(lines, budget, usize::MAX);
        }
        let left = self.grammar.is_some() && !self.synced(lines).invalid.is_empty();
        if !left {
            self.background_scheduled.set(false);
        }
        left
    }

    /// Tokenizes lines with an untrusted end state, at least one, until `budget` has passed or `max_lines` are done.
    fn tokenize_for(&self, lines: &[String], budget: Duration, max_lines: usize) {
        let started = Instant::now();
        let mut store = self.synced(lines);
        let mut tokenized = 0;
        while let Some(line) = store.invalid.min() {
            self.tokenize_line(&mut store, lines, line);
            tokenized += 1;
            if started.elapsed() > budget || tokenized == max_lines {
                break;
            }
        }
    }

    /// The store, reset when the document has another line count than it tracks (also before the first read).
    fn synced(&self, lines: &[String]) -> std::cell::RefMut<'_, TokenStore> {
        let mut store = self.lines.borrow_mut();
        if store.tokens.len() != lines.len() {
            store.reset(lines.len());
        }
        store
    }

    fn tokenize_line(&self, store: &mut TokenStore, lines: &[String], line: usize) {
        let grammar = self.grammar.as_ref().expect("tokenized with a grammar");
        let previous = match line {
            0 => None,
            _ => Some(store.end_states[line - 1].as_ref().expect("a line before the first untrusted one has its end state")),
        };
        let (tokens, state) = tokenize_text(grammar, lines, line, previous);
        store.tokens[line] = tokens;
        store.brackets.lines[line] = None;
        store.plain_brackets.lines[line] = None;
        *self.brackets.borrow_mut() = None;
        store.set_end_state(line, state);
    }
}

/// `safeTokenize` of line `line` after `previous` (none at the grammar's start): a line longer than
/// `MAX_TOKENIZATION_LINE_LENGTH` gets no tokens and passes the state through.
fn tokenize_text(grammar: &Grammar, lines: &[String], line: usize, previous: Option<&State>) -> (Vec<Token>, State) {
    let text = &lines[line];
    let result = if text.encode_utf16().count() > MAX_TOKENIZATION_LINE_LENGTH {
        None
    } else {
        // A grammar regex Oniguruma cannot run leaves the line without tokens, as nullTokenize does upstream.
        grammar.tokenize_line(text, previous).map_err(|error| eprintln!("tokenizing line {}: {error}", line + 1)).ok()
    };
    match (result, previous) {
        (Some(entry), _) => entry,
        (None, Some(state)) => (Vec::new(), state.clone()),
        (None, None) => (Vec::new(), grammar.tokenize_line("", None).expect("an empty line tokenizes").1),
    }
}

/// textModelTokens.ts `guessStartState` with `findLikelyRelevantLines`: the lines above `line` each less indented
/// than the one below, up to one whose start state is known, tokenized from that state; none is the grammar's start.
fn guess_start_state(grammar: &Grammar, store: &TokenStore, lines: &[String], line: usize) -> Option<State> {
    // `getLineFirstNonWhitespaceColumn`: 1-based, 0 for a line of spaces and tabs only.
    let first_non_whitespace_column = |text: &str| text.find(|char| char != ' ' && char != '\t').map_or(0, |index| index + 1);
    let mut column = first_non_whitespace_column(&lines[line]);
    let mut relevant = Vec::new();
    let mut initial_state = None;
    for above in (0..line).rev() {
        if column <= 1 {
            break;
        }
        let above_column = first_non_whitespace_column(&lines[above]);
        if above_column == 0 || above_column >= column {
            continue;
        }
        relevant.push(above);
        column = above_column;
        // `getStartState`: line 0 starts in the grammar's start state, another after the end state above it.
        let start_state = if above == 0 { Some(None) } else { store.end_states[above - 1].as_ref().map(Some) };
        if let Some(start_state) = start_state {
            initial_state = start_state.cloned();
            break;
        }
    }
    let mut state = initial_state;
    for &relevant_line in relevant.iter().rev() {
        state = Some(tokenize_text(grammar, lines, relevant_line, state.as_ref()).1);
    }
    state
}

/// The non-transparent `editorBracketHighlight.foreground1..6`, the colors levels cycle through.
fn bracket_colors(theme: &Theme) -> Vec<Hsla> {
    (1..=6).filter_map(|n| theme.color(&format!("editorBracketHighlight.foreground{n}"))).filter(|color| color.a > 0.).map(Into::into).collect()
}

/// The bracket colors over the token styles: a bracket keeps its token's font style.
pub(crate) fn overlay_colors(highlights: Vec<(Range<usize>, HighlightStyle)>, colors: &[(Range<usize>, Hsla)]) -> Vec<(Range<usize>, HighlightStyle)> {
    let mut result = Vec::new();
    for (range, style) in highlights {
        let mut start = range.start;
        for (bracket, color) in colors.iter().filter(|(bracket, _)| bracket.start < range.end && bracket.end > range.start) {
            let (bracket_start, bracket_end) = (bracket.start.max(range.start), bracket.end.min(range.end));
            if start < bracket_start {
                result.push((start..bracket_start, style));
            }
            let recolored = HighlightStyle {
                color: Some(*color),
                underline: style.underline.map(|underline| UnderlineStyle { color: Some(*color), ..underline }),
                strikethrough: style.strikethrough.map(|strikethrough| StrikethroughStyle { color: Some(*color), ..strikethrough }),
                ..style
            };
            result.push((bracket_start..bracket_end, recolored));
            start = bracket_end;
        }
        if start < range.end {
            result.push((start..range.end, style));
        }
    }
    result
}

/// The `.mtk*` styles of a line's tokens (`generateTokensCSSForColorMap`) over its tab-expanded text:
/// token backgrounds are not drawn, as in the editor.
fn token_highlights(theme: &textmate::Theme, text: &str, tokens: &[Token], tab_size: usize) -> Vec<(Range<usize>, HighlightStyle)> {
    let expanded_offset = expanded_offsets(text, tab_size);
    let color_map = theme.color_map();
    tokens
        .iter()
        .filter(|token| token.start < token.end.min(text.len()))
        .map(|token| {
            let style = theme.style(&token.scopes);
            let range = expanded_offset[token.start]..expanded_offset[token.end.min(text.len())];
            let color = color_map.get(style.foreground).and_then(|hex| Rgba::try_from(hex.as_str()).ok());
            let font_style = style.font_style.max(0);
            let highlight = HighlightStyle {
                color: color.map(Into::into),
                font_style: (font_style & textmate::ITALIC != 0).then_some(FontStyle::Italic),
                font_weight: (font_style & textmate::BOLD != 0).then_some(FontWeight::BOLD),
                underline: (font_style & textmate::UNDERLINE != 0).then(|| UnderlineStyle { thickness: px(1.), color: color.map(Into::into), wavy: false }),
                strikethrough: (font_style & textmate::STRIKETHROUGH != 0).then(|| StrikethroughStyle { thickness: px(1.), color: color.map(Into::into) }),
                ..Default::default()
            };
            (range, highlight)
        })
        .collect()
}

/// For each byte offset of `text` (and its end), the offset in `expand_tabs(text, tab_size)`.
fn expanded_offsets(text: &str, tab_size: usize) -> Vec<usize> {
    let mut offsets = vec![0; text.len() + 1];
    let (mut expanded, mut visible) = (0, 0);
    for (index, c) in text.char_indices() {
        for byte in 0..c.len_utf8() {
            offsets[index + byte] = expanded;
        }
        let width = crate::editor::char_columns(c, visible, tab_size);
        // `expand_tabs` draws a tab and a bidi format character as spaces.
        expanded += if c == '\t' || crate::editor::is_bidi_format_character(c) { width } else { c.len_utf8() };
        visible += width;
    }
    offsets[text.len()] = expanded;
    offsets
}

#[cfg(test)]
mod tests {
    use std::path::{Path, PathBuf};
    use std::rc::Rc;

    use serde_json::Value;
    use textmate::ScopeStack;

    use super::*;
    use crate::languages::Languages;
    use crate::theme::load_theme;

    /// The default themes the colorize results hold, by file name (`getThemeName` in themes.test.contribution.ts).
    const THEMES: [&str; 10] = ["dark_plus", "light_plus", "dark_vs", "light_vs", "hc_black", "dark_modern", "hc_light", "light_modern", "2026-dark", "2026-light"];

    /// `Snapper._tokenize`: per line, consecutive tokens with equal scopes merged.
    fn capture_tokens(languages: &Languages, language: &str, content: &str) -> Vec<(String, Rc<ScopeStack>)> {
        let grammar = languages.grammars.grammar(language).unwrap_or_else(|| panic!("no grammar for {language}"));
        let mut result: Vec<(String, Rc<ScopeStack>)> = Vec::new();
        let mut state = None;
        for line in content.split("\r\n").flat_map(|line| line.split(['\r', '\n'])) {
            let (tokens, next) = grammar.tokenize_line(line, state.as_ref()).unwrap();
            let mut last_scopes: Option<String> = None;
            for token in tokens {
                let text = &line[token.start.min(line.len())..token.end.min(line.len())];
                let scopes = token.scopes.names().join(" ");
                if last_scopes.as_deref() == Some(scopes.as_str()) {
                    result.last_mut().unwrap().0.push_str(text);
                } else {
                    result.push((text.to_string(), token.scopes.clone()));
                    last_scopes = Some(scopes);
                }
            }
            state = Some(next);
        }
        result
    }

    #[test]
    fn force_retokenize_tokenizes_every_line_again() {
        let extensions = exthost::scan::scan_builtin_extensions(&Path::new(env!("VSCODE_SRC")).join("extensions")).unwrap();
        let languages = Languages::new(&extensions);
        let lines: Vec<String> = ["let a = 1;", "/* open", "still comment */", "a;"].map(String::from).into();
        let mut tokens = Tokenization::new(languages.grammars.grammar("typescript"));
        tokens.tokenize_to(&lines, 0);
        tokens.force_retokenize(&lines);
        assert_eq!(tokens.lines.borrow().tokens.len(), 4);
        assert!(tokens.line_tokens(&lines, 2).iter().all(|(_, token_type, _)| *token_type == textmate::StandardTokenType::Comment));
        Tokenization::new(None).force_retokenize(&lines);
    }

    // Issue 116: each document compiled its own grammar (3.3 MB for TypeScript) and each token held its own scopes.
    #[test]
    fn documents_share_the_grammar_and_tokens_share_their_scopes() {
        let extensions = exthost::scan::scan_builtin_extensions(&Path::new(env!("VSCODE_SRC")).join("extensions")).unwrap();
        let languages = Languages::new(&extensions);
        let grammar = languages.grammars.grammar("typescript").unwrap();
        assert!(Rc::ptr_eq(&grammar, &languages.grammars.grammar("typescript").unwrap()));
        let (first, state) = grammar.tokenize_line("let a = 1;", None).unwrap();
        let (second, _) = grammar.tokenize_line("let b = 2;", Some(&state)).unwrap();
        assert!(Rc::ptr_eq(&first[0].scopes, &second[0].scopes), "{:?}", first[0].scopes.names());
    }

    /// An edit that leaves a line's end state as it was retokenizes that line only; one that changes it carries on
    /// down, line by line, as far as the lines are read.
    #[test]
    fn an_unchanged_end_state_stops_the_retokenizing() {
        let extensions = exthost::scan::scan_builtin_extensions(&Path::new(env!("VSCODE_SRC")).join("extensions")).unwrap();
        let languages = Languages::new(&extensions);
        let mut lines: Vec<String> = ["let a = 1;", "let b = 2;", "let c = 3;", "let d = 4;"].map(String::from).into();
        let mut tokens = Tokenization::new(languages.grammars.grammar("typescript"));
        tokens.tokenize_to(&lines, 3);
        lines[1] = "let bb = 2;".into();
        tokens.accept_edit(1, 1, 1);
        tokens.tokenize_to(&lines, 1);
        assert_eq!(tokens.lines.borrow().invalid.min(), None);
        lines[1] = "/* let bb = 2;".into();
        tokens.accept_edit(1, 1, 1);
        tokens.tokenize_to(&lines, 1);
        assert_eq!(tokens.lines.borrow().invalid.min(), Some(2));
        assert!(tokens.tokenize_in_background(&lines, std::time::Duration::ZERO), "one line per call at least");
        assert!(!tokens.tokenize_in_background(&lines, std::time::Duration::from_secs(1)));
        assert!(tokens.line_tokens(&lines, 3).iter().all(|(_, token_type, _)| *token_type == textmate::StandardTokenType::Comment));
        lines.splice(1..3, ["let b = 2;".to_string()]);
        tokens.accept_edit(1, 2, 1);
        assert_eq!(tokens.lines.borrow().tokens.len(), 3);
        assert_eq!(tokens.line_tokens(&lines, 2).iter().find(|(_, token_type, _)| *token_type == textmate::StandardTokenType::Comment), None);
    }

    /// `tokenizeIfCheap` tokenizes only the first untrusted line; a line past it is read with the tokens it has and
    /// keeps no accurate tokens (`hasAccurateTokensForLine`).
    #[test]
    fn only_the_first_untrusted_line_is_cheap_to_tokenize() {
        let extensions = exthost::scan::scan_builtin_extensions(&Path::new(env!("VSCODE_SRC")).join("extensions")).unwrap();
        let languages = Languages::new(&extensions);
        let lines: Vec<String> = ["let a = 1;", "let b = 2;", "let c = 3;"].map(String::from).into();
        let tokens = Tokenization::new(languages.grammars.grammar("typescript"));
        tokens.language_at_if_cheap(&lines, 2, 0);
        assert!(!tokens.has_accurate_tokens_for_line(&lines, 0));
        tokens.language_at_if_cheap(&lines, 0, 0);
        assert!(tokens.has_accurate_tokens_for_line(&lines, 0));
        assert!(!tokens.has_accurate_tokens_for_line(&lines, 1));
        assert!(Tokenization::new(None).has_accurate_tokens_for_line(&lines, 2));
    }

    /// textModelTokens.ts `tokenizeHeuristically`: lines in view far below the tokenized ones get their tokens from a
    /// state guessed from the less indented lines above, without the lines between; the background tokenizes them again.
    #[test]
    fn lines_in_view_past_the_tokenized_ones_are_tokenized_from_a_guessed_state() {
        let extensions = exthost::scan::scan_builtin_extensions(&Path::new(env!("VSCODE_SRC")).join("extensions")).unwrap();
        let languages = Languages::new(&extensions);
        let lines: Vec<String> = (0..5000).flat_map(|index| [format!("class C{index} {{"), "  run() {".into(), "    return `a${b}`;".into(), "  }".into(), "}".into()]).collect();
        let scopes = |tokens: &Tokenization, line: usize| tokens.lines.borrow().tokens[line].iter().map(|token| token.scopes.names().join(" ")).collect::<Vec<_>>();
        let accurate = Tokenization::new(languages.grammars.grammar("typescript"));
        accurate.tokenize_to(&lines, 20_060);
        let mut tokens = Tokenization::new(languages.grammars.grammar("typescript"));
        tokens.tokenize_viewport(&lines, 20_002, 20_060);
        assert_eq!(tokens.lines.borrow().invalid.min(), Some(0), "the lines above the view are left to the background");
        assert_eq!(scopes(&tokens, 20_002), scopes(&accurate, 20_002), "the guessed state is the class's method body");
        assert!(tokens.highlights(&load_theme(&extensions, "Dark Modern").unwrap(), &languages, &lines, 100, 4).is_empty(), "the view reads the tokens as they are");
        while tokens.tokenize_in_background(&lines, std::time::Duration::from_secs(1)) {}
        assert_eq!(tokens.lines.borrow().invalid.min(), None);
        assert_eq!(scopes(&tokens, 20_060), scopes(&accurate, 20_060));
    }

    /// Each line's brackets are found again after an edit to it, and after a retokenizing that changed its tokens.
    #[test]
    fn a_line_s_brackets_are_read_again_when_its_text_or_tokens_change() {
        let extensions = exthost::scan::scan_builtin_extensions(&Path::new(env!("VSCODE_SRC")).join("extensions")).unwrap();
        let languages = Languages::new(&extensions);
        let mut lines: Vec<String> = ["f(1);", "g(2);"].map(String::from).into();
        let mut tokens = Tokenization::new(languages.grammars.grammar("typescript"));
        assert_eq!(tokens.pairs(&languages, &lines, "typescript").pairs_in_lines(0..lines.len()).len(), 2);
        lines[0] = "f((1);".into();
        tokens.accept_edit(0, 0, 1);
        assert_eq!(tokens.pairs(&languages, &lines, "typescript").pairs_in_lines(0..lines.len()).len(), 3);
        lines[0] = "/* f(1);".into();
        tokens.accept_edit(0, 0, 1);
        assert_eq!(tokens.pairs(&languages, &lines, "typescript").pairs_in_lines(0..lines.len()).len(), 0, "the comment opened above hides line 2's brackets");
    }

    /// bracketPairsTree.ts `handleDidChangeTokens`: lines the view tokenizes after the pairs were read get their
    /// bracket colors on the next read, though no background tokenization is left to run.
    #[test]
    fn brackets_follow_lines_tokenized_after_the_pairs_were_read() {
        let extensions = exthost::scan::scan_builtin_extensions(&Path::new(env!("VSCODE_SRC")).join("extensions")).unwrap();
        let languages = Languages::new(&extensions);
        let theme = load_theme(&extensions, "Dark Modern").unwrap();
        let lines: Vec<String> = (0..BRACKET_TOKENIZE_LINES + 10).map(|_| "f(1);".to_owned()).collect();
        let mut tokens = Tokenization::new(languages.grammars.grammar("typescript"));
        let colored = tokens.highlights(&theme, &languages, &lines, 0, 4);
        let last = lines.len() - 1;
        tokens.highlights(&theme, &languages, &lines, last, 4);
        assert!(!tokens.tokenize_in_background(&lines, Duration::from_secs(1)), "the view tokenized every line");
        assert_eq!(tokens.highlights(&theme, &languages, &lines, last, 4), colored);
    }

    /// Typing latency on a 52k-line TypeScript file (textModel.ts repeated): the median per edit of one typed char
    /// then the tokens of 60 visible lines, the bracket match, the section headers and the unicode highlights, at lines
    /// 100, 25000 and 49000; the gate is a p95 under 16 ms per edit. Also the gates of port/notes.md "Scheduling differences".
    /// Run in release: `cargo gc test --release -p app -- --ignored typing_latency_on_a_large_file --nocapture`.
    #[test]
    #[ignore]
    fn typing_latency_on_a_large_file() {
        let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
        let extensions = exthost::scan::scan_builtin_extensions(&app_root.join("extensions")).unwrap();
        let languages = Languages::new(&extensions);
        let theme = load_theme(&extensions, "Dark Modern").unwrap();
        let source = std::fs::read_to_string(app_root.join("src/vs/editor/common/model/textModel.ts")).unwrap();
        let mut text = String::new();
        while text.lines().count() < 50_000 {
            text.push_str(&source);
        }
        let path = std::env::temp_dir().join(format!("code-gpui-latency-{}.ts", std::process::id()));
        std::fs::write(&path, &text).unwrap();
        let document = crate::editor::TextDocument::read(&path, &languages, &crate::default_settings().lock().unwrap()).unwrap();
        std::fs::remove_file(&path).unwrap();
        let mut group = crate::editor::EditorGroup::default();
        group.open(document, false);
        let editor = group.active_mut().unwrap();
        let unicode_options = crate::editor::unicode_highlighter::UnicodeHighlighterOptions {
            non_basic_ascii: false,
            ambiguous_characters: true,
            invisible_characters: true,
            include_comments: false,
            include_strings: true,
            allowed_code_points: Vec::new(),
            allowed_locales: vec!["en".into()],
        };
        let frame = |editor: &crate::editor::OpenEditor, line: usize, column: usize| {
            let document = editor.document();
            let lines = &document.lines;
            document.tokens.tokenize_viewport(lines, line.saturating_sub(30), line + 29);
            for index in line.saturating_sub(30)..(line + 30).min(lines.len()) {
                document.tokens.highlights(&theme, &languages, lines, index, 4);
            }
            document.tokens.bracket_match(&theme, &languages, lines, (line, column));
            // The workbench's section headers (minimap_view.rs `section_headers`) and unicode highlights of each model version.
            let find = crate::editor::section_headers::FindOptions {
                region_start: document.folding_markers.as_deref().map(|markers| &markers.start_with_flags),
                mark_regex: Some(crate::editor::section_headers::MARK_SECTION_HEADER_REGEX),
                block_comment: document.block_comment.as_ref().map(|(start, end)| (start.as_str(), end.as_str())),
            };
            for header in crate::editor::section_headers::find_section_headers(lines, &find).iter().filter(|header| header.should_be_in_comments) {
                document.tokens.stored_token_type_at(lines, header.start.line, 0);
            }
            crate::editor::unicode_highlighter::compute_unicode_highlights(lines, 0, &unicode_options);
        };
        let background = |editor: &mut crate::editor::OpenEditor| {
            let mut document = editor.document_mut();
            let document = &mut *document;
            while document.tokens.tokenize_in_background(&document.lines, Duration::from_millis(1)) {}
        };
        let start = Instant::now();
        frame(editor, 0, 0);
        eprintln!("{} lines, first frame {:?}", editor.document().lines.len(), start.elapsed());
        let start = Instant::now();
        background(editor);
        frame(editor, 0, 0);
        eprintln!("background tokenization and the next frame {:?}", start.elapsed());
        let mut p95s = Vec::new();
        for line in [100, 25_000, 49_000] {
            editor.move_to(crate::editor::Position::new(line, 0), false);
            frame(editor, line, 0);
            let mut times = Vec::new();
            for column in 1..=41 {
                let start = Instant::now();
                editor.type_text("x").unwrap();
                frame(editor, line, column);
                background(editor);
                times.push(start.elapsed().as_secs_f64() * 1000.);
            }
            times.sort_by(f64::total_cmp);
            // Nearest-rank p95 of 41 edits is the 39th.
            eprintln!("line {line}: median {:.2} ms, p95 {:.2} ms, max {:.2} ms", times[20], times[38], times[40]);
            p95s.push(times[38]);
        }
        // bracketSelections.ts yields after `_maxDuration` (30 ms): a scan under it gives upstream's ranges.
        let mut bracket_scans = Vec::new();
        for line in [100, 25_010, 49_010] {
            editor.type_text("x").unwrap();
            background(editor);
            let position = crate::editor::Position::new(line, 9);
            editor.bracket_selection_ranges(&languages, position);
            let start = Instant::now();
            editor.bracket_selection_ranges(&languages, position);
            bracket_scans.push(start.elapsed().as_secs_f64() * 1000.);
        }
        eprintln!("bracket selection scans {bracket_scans:.2?} ms");
        // `tokenizeIfCheap` and `hasAccurateTokensForLine`: on a file just opened, trim and comment tokenize no far lines.
        std::fs::write(&path, &text).unwrap();
        let document = crate::editor::TextDocument::read(&path, &languages, &crate::default_settings().lock().unwrap()).unwrap();
        std::fs::remove_file(&path).unwrap();
        let mut group = crate::editor::EditorGroup::default();
        group.open(document, false);
        let editor = group.active_mut().unwrap();
        frame(editor, 0, 0);
        editor.move_to(crate::editor::Position::new(49_000, 0), false);
        let start = Instant::now();
        editor.trim_trailing_whitespace(false);
        let trim = start.elapsed().as_secs_f64() * 1000.;
        let start = Instant::now();
        editor.comment_lines(crate::editor::LineCommentKind::Toggle, true, true, &languages);
        let comment = start.elapsed().as_secs_f64() * 1000.;
        eprintln!("on a file just opened: trim {trim:.2} ms, comment at line 49000 {comment:.2} ms");
        assert!(p95s.iter().all(|&p95| p95 < 16.), "p95 per edit {p95s:?} ms, the gate is 16 ms");
        assert!(bracket_scans.iter().all(|&scan| scan < 30.), "bracket selection scans {bracket_scans:?} ms, upstream yields at 30 ms");
        assert!(trim < 16. && comment < 16., "trim {trim} ms, comment {comment} ms, the gate is 16 ms");
    }

    /// Every colorize-tests fixture gives the reference's tokens, scopes and, in each default theme, colors.
    #[test]
    fn colorize_fixtures_match_the_reference() {
        let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
        let extensions = exthost::scan::scan_builtin_extensions(&app_root.join("extensions")).unwrap();
        let languages = Languages::new(&extensions);
        let defaults = extensions.iter().find(|extension| extension.location.ends_with("theme-defaults")).unwrap();
        let themes: Vec<_> = THEMES
            .iter()
            .map(|name| {
                let contribution = defaults.description["contributes"]["themes"].as_array().unwrap().iter().find(|theme| theme["path"] == format!("./themes/{name}.json")).unwrap();
                let id = contribution["id"].as_str().or(contribution["label"].as_str()).unwrap();
                (*name, load_theme(&extensions, id).unwrap())
            })
            .collect();
        let tests = app_root.join("extensions/vscode-colorize-tests/test");
        let mut fixtures: Vec<PathBuf> = std::fs::read_dir(tests.join("colorize-fixtures")).unwrap().map(|entry| entry.unwrap().path()).collect();
        fixtures.sort();
        let mut failures = Vec::new();
        for fixture in &fixtures {
            let name = fixture.file_name().unwrap().to_string_lossy();
            let results = tests.join("colorize-results").join(format!("{}.json", name.replacen('.', "_", 1)));
            let expected: Vec<Value> = serde_json::from_str(&std::fs::read_to_string(&results).unwrap()).unwrap();
            let content = std::fs::read_to_string(fixture).unwrap();
            let language = languages.language_of(fixture, content.split(['\r', '\n']).next().unwrap());
            let actual = capture_tokens(&languages, language, &content);
            let actual: Vec<_> = actual.into_iter().filter(|(text, _)| !text.is_empty()).collect();
            for index in 0..expected.len().max(actual.len()) {
                let (Some(want), Some((text, scopes))) = (expected.get(index), actual.get(index)) else {
                    failures.push(format!("{name}: {} tokens, the reference has {}", actual.len(), expected.len()));
                    break;
                };
                let names = scopes.names().join(" ");
                if want["c"] != text.as_str() || want["t"] != names.as_str() {
                    failures.push(format!("{name}: token {index}: expected {:?} {:?}, got {text:?} {names:?}", want["c"], want["t"]));
                    break;
                }
                for (theme_name, theme) in &themes {
                    let Some(explanation) = want["r"][theme_name].as_str() else { continue };
                    let want_color = explanation.rsplit(": ").next().unwrap();
                    let color = &theme.tokens.color_map()[theme.tokens.style(scopes).foreground];
                    if want_color != color {
                        failures.push(format!("{name}: token {index} {text:?} in {theme_name}: expected {explanation}, got {color}"));
                    }
                }
            }
        }
        assert!(failures.is_empty(), "{} mismatches over {} fixtures:\n{}", failures.len(), fixtures.len(), failures.join("\n"));
    }

    /// An edit recolors the text: the tokens drawn after it equal a fresh tokenization of the new text.
    #[test]
    fn edits_drop_stale_tokens_and_brackets() {
        let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
        let extensions = exthost::scan::scan_builtin_extensions(&app_root.join("extensions")).unwrap();
        let languages = Languages::new(&extensions);
        let theme = load_theme(&extensions, "Dark Modern").unwrap();
        let path = std::env::temp_dir().join(format!("code-gpui-tokens-{}.ts", std::process::id()));
        std::fs::write(&path, "let a = (1);\nlet b = 2;\n").unwrap();
        let document = crate::editor::TextDocument::read(&path, &languages, &crate::default_settings().lock().unwrap()).unwrap();
        std::fs::remove_file(&path).unwrap();
        let mut group = crate::editor::EditorGroup::default();
        group.open(document, false);
        let editor = group.active_mut().unwrap();
        let highlights = |editor: &crate::editor::OpenEditor, index| editor.document().tokens.highlights(&theme, &languages, &editor.document().lines, index, 4);
        let before = (highlights(editor, 0), highlights(editor, 1));
        assert!(editor.document().tokens.bracket_match(&theme, &languages, &editor.document().lines, (0, 8)).is_some());

        editor.move_to(crate::editor::Position::new(0, 0), false);
        editor.type_text("/* ").unwrap();
        let fresh = Tokenization::new(languages.grammars.grammar("typescript"));
        let lines = editor.document().lines.clone();
        for index in 0..2 {
            assert_eq!(highlights(editor, index), fresh.highlights(&theme, &languages, &lines, index, 4), "line {index}");
        }
        assert_ne!((highlights(editor, 0), highlights(editor, 1)), before);
        assert!(editor.document().tokens.bracket_match(&theme, &languages, &lines, (0, 11)).is_none());
    }

    #[test]
    fn normalizes_colors_like_color_theme_data() {
        assert_eq!(normalize_color("#abc").as_deref(), Some("#AABBCC"));
        assert_eq!(normalize_color("#abcdefff").as_deref(), Some("#ABCDEF"));
        assert_eq!(normalize_color("#abcdef80").as_deref(), Some("#ABCDEF80"));
        assert_eq!(normalize_color("abcdef"), None);
        assert_eq!(normalize_color("#abcdeg"), None);
        assert_eq!(expanded_offsets("\ta\u{e9}", 4), [0, 4, 5, 5, 7]);
    }
}