Skip to content

Visual Studio Code, rebuilt in Rust

Rust

perf(editor): parse bracket pairs incrementally with the bracket tree

rokarturbd72dafb8022
diff --git a/native/crates/app/src/brackets.rs b/native/crates/app/src/brackets.rs
index 6015f9769f3..2aa04bf2624 100644
--- a/native/crates/app/src/brackets.rs
+++ b/native/crates/app/src/brackets.rs
@@ -2,6 +2,11 @@
//! 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;
@@ -9,6 +14,11 @@ 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>>,
@@ -19,10 +29,12 @@ 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: Vec<String>,
+ ids: BracketIds,
/// The opening brackets a closing one closes as a colorized pair.
- colorized_openings: Vec<String>,
+ colorized_openings: BracketIds,
}
impl LanguageBrackets {
@@ -57,10 +69,12 @@ impl LanguageBrackets {
}
let mut tokens = HashMap::new();
for open in openings {
- tokens.insert(open.to_string(), Arc::new(BracketToken { opening: true, id: id(open), ids: vec![id(open)], colorized_openings: Vec::new() }));
+ 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 {
- tokens.insert(close.to_string(), Arc::new(BracketToken { opening: false, id: opened[0].clone(), ids: opened, colorized_openings }));
+ 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();
@@ -80,7 +94,7 @@ impl LanguageBrackets {
/// `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.contains(&open.id)
+ !close.opening && close.ids.has(open.key)
}
/// `text.replace(getBracketRegExp({ global: true }), '')`: the text without any bracket.
@@ -173,83 +187,136 @@ pub struct PairBracket {
pub key: String,
}
-/// The brackets of a whole document: the colorized brackets of each line
-/// (`getBracketsInRange(range, true)`), every pair, outer pairs first (`getBracketPairsInRange`), and
-/// every bracket of a pair in document order (`getFirstBracketAfter`/`Before` skip unexpected closings).
-#[derive(Default)]
+/// 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 {
- pub lines: Vec<Vec<Bracket>>,
- pub pairs: Vec<Pair>,
- pub brackets: Vec<PairBracket>,
+ 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 document_end = lines.last().map_or((0, 0), |(text, _)| (lines.len() - 1, text.len()));
- DocumentBrackets::from_lines(&found, document_end)
+ let lengths: Vec<_> = lines.iter().map(|(text, _)| text.len()).collect();
+ DocumentBrackets { root: tree::parse_document(&found, &lengths, &[], None) }
}
- /// The pairs over the brackets of each line; an unclosed pair at the end runs to `document_end`.
- pub fn from_lines(lines: &[&[LineBracket]], document_end: (usize, usize)) -> Self {
+ /// The colorized brackets of line `line`.
+ pub fn line(&self, line: usize) -> Vec<Bracket> {
let mut found = Vec::new();
- for (line, brackets) in lines.iter().enumerate() {
- found.extend(brackets.iter().map(|bracket| Found { line, range: bracket.range.clone(), token: &bracket.token }));
- }
- let mut parser = Parser { found: &found, next: 0, document_end };
- let mut nodes = Vec::new();
- while parser.next < found.len() {
- nodes.extend(parser.parse_child(&[], 1));
+ 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)),
}
- let mut result = DocumentBrackets { lines: vec![Vec::new(); lines.len()], pairs: Vec::new(), brackets: Vec::new() };
- collect(&nodes, &found, 0, &mut result.lines);
- collect_pairs(&nodes, &found, 0, &mut result.pairs);
- collect_pair_brackets(&nodes, &found, &mut result.brackets);
- result
}
/// `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]> {
+ 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 {
- let Some(close) = &pair.close else { continue };
+ 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
- } else if touches(close) {
- close
+ pair.open.clone()
+ } else if touches(&close) {
+ close.clone()
} else {
continue;
};
- if best.is_none_or(|(best, _)| (bracket.0, bracket.1.start) >= (best.0, best.1.start)) {
- best = Some((bracket, [&pair.open, close]));
+ 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> {
- self.brackets.iter().map(|bracket| &bracket.range).find(|(bracket_line, range)| (*bracket_line, range.end) > (line, offset))
+ 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.iter().rev().find_map(|pair| {
- let close = pair.close.as_ref()?;
+ 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])
+ (after_open && before_close).then_some([pair.open, close])
})
}
+
+ /// 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
+ }
}
-struct Found<'a> {
- line: usize,
- range: Range<usize>,
- token: &'a BracketToken,
+/// 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.
@@ -293,118 +360,107 @@ pub fn line_brackets(text: &str, spans: &[Span], languages: &HashMap<String, Lan
found
}
-enum Node {
- Pair { open: usize, children: Vec<Node>, close: Option<usize>, end: (usize, usize) },
- Unexpected(usize),
-}
-
-/// `Parser` (parser.ts) without the incremental reuse: an opening bracket starts a pair that a closing
-/// bracket of the same set ends; a closing bracket of an outer pair ends the inner ones unclosed.
-struct Parser<'a> {
- found: &'a [Found<'a>],
- next: usize,
- document_end: (usize, usize),
+/// 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)
}
-impl Parser<'_> {
- fn parse_list(&mut self, opened: &[&str], level: usize) -> Vec<Node> {
- let mut items = Vec::new();
- while let Some(next) = self.found.get(self.next) {
- if !next.token.opening && intersects(&next.token.ids, opened) {
- break;
- }
- items.extend(self.parse_child(opened, level + 1));
- }
- items
+/// `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;
}
-
- fn parse_child(&mut self, opened: &[&str], level: usize) -> Option<Node> {
- let index = self.next;
- self.next += 1;
- let token = self.found[index].token;
- if !token.opening {
- return Some(Node::Unexpected(index));
- }
- // Deeper openings read as text.
- if level > 300 {
- return None;
- }
- let mut set = opened.to_vec();
- for id in &token.ids {
- if !set.contains(&id.as_str()) {
- set.push(id);
+ 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;
}
}
- let children = self.parse_list(&set, level + 1);
- let mut close = None;
- if let Some(next) = self.found.get(self.next)
- && !next.token.opening
- && (next.token.id == token.id || next.token.ids.iter().any(|id| token.ids.contains(id)))
- {
- close = Some(self.next);
- self.next += 1;
+ 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;
+ }
}
- // An unclosed pair ends where the bracket that stopped its parse starts.
- let end = match close {
- Some(close) => (self.found[close].line, self.found[close].range.end),
- None => self.found.get(self.next).map_or(self.document_end, |next| (next.line, next.range.start)),
- };
- Some(Node::Pair { open: index, children, close, end })
}
}
-fn collect_pair_brackets(nodes: &[Node], found: &[Found], result: &mut Vec<PairBracket>) {
- for node in nodes {
- let Node::Pair { open, children, close, .. } = node else { continue };
- let bracket = |index: usize| PairBracket { range: (found[index].line, found[index].range.clone()), opening: found[index].token.opening, key: found[index].token.id.clone() };
- result.push(bracket(*open));
- collect_pair_brackets(children, found, result);
- if let Some(close) = close {
- result.push(bracket(*close));
+/// `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;
}
}
-fn intersects(ids: &[String], opened: &[&str]) -> bool {
- ids.iter().any(|id| opened.contains(&id.as_str()))
-}
-
-/// `collectBrackets` with `onlyColorizedBrackets`: 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(nodes: &[Node], found: &[Found], level: isize, result: &mut [Vec<Bracket>]) {
- if level > 200 {
+/// 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;
}
- for node in nodes {
- match node {
- Node::Unexpected(index) => push(result, &found[*index], level - 1, true),
- Node::Pair { open, children, close, .. } => {
- let colorize = close.is_none_or(|close| found[close].token.colorized_openings.contains(&found[*open].token.id));
- let child_level = if colorize { level + 1 } else { level };
- let visible = colorize && child_level <= 200;
- if visible {
- push(result, &found[*open], child_level - 1, close.is_none());
- }
- collect(children, found, child_level, result);
- if let Some(close) = close
- && visible
- {
- push(result, &found[*close], child_level - 1, false);
- }
- }
- }
+ let mut child_start = start;
+ for child in node.children() {
+ collect_pair_brackets(child, child_start, brackets);
+ child_start = child_start + child.length();
}
}
-/// `collectBracketPairs`: every pair, colorized or not, before the pairs inside it.
-fn collect_pairs(nodes: &[Node], found: &[Found], level: usize, pairs: &mut Vec<Pair>) {
- for node in nodes {
- if let Node::Pair { open, children, close, end } = node {
- let range = |index: usize| (found[index].line, found[index].range.clone());
- pairs.push(Pair { open: range(*open), close: close.map(range), end: *end, level });
- collect_pairs(children, found, level + 1, pairs);
+/// `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`.
@@ -512,10 +568,6 @@ fn min_indentation(lines: &[String], tab_size: usize, inside: Range<usize>) -> u
min
}
-fn push(result: &mut [Vec<Bracket>], found: &Found, level: isize, invalid: bool) {
- result[found.line].push(Bracket { range: found.range.clone(), level, invalid });
-}
-
#[cfg(test)]
mod tests {
use serde_json::json;
@@ -527,7 +579,7 @@ mod tests {
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).lines[0].iter().map(|b| (b.level, b.range.clone(), b.invalid)).collect()
+ DocumentBrackets::new(&[(text, vec![span])], &languages).line(0).into_iter().map(|b| (b.level, b.range, b.invalid)).collect()
}
fn colorized_config() -> Value {
@@ -547,15 +599,16 @@ mod tests {
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.iter().map(|id| strip(id)).collect::<Vec<_>>())
+ (token.opening, strip(&token.id), token.ids.clone())
};
- assert_eq!(token("begin"), (true, "begin".into(), vec!["begin".into()]));
- assert_eq!(token("\\left."), (true, "\\left.".into(), vec!["\\left.".into()]));
- assert_eq!(token("end"), (false, "begin".into(), vec!["begin".into()]));
- assert_eq!(token("endcase"), (false, "case".into(), vec!["case".into(), "casez".into()]));
- assert_eq!(token("\\right)"), (false, "\\left(".into(), vec!["\\left(".into(), "\\left.".into()]));
- assert_eq!(token("\\right."), (false, "\\left(".into(), vec!["\\left(".into(), "\\left[".into()]));
- assert_eq!(token("\\right]"), (false, "\\left[".into(), vec!["\\left[".into(), "\\left.".into()]));
+ 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.
@@ -587,7 +640,7 @@ mod tests {
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()));
+ 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)));
@@ -609,7 +662,7 @@ mod tests {
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;
+ 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));
@@ -627,7 +680,7 @@ mod tests {
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;
+ 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 };
@@ -640,4 +693,93 @@ mod tests {
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:?}");
+ }
+ }
+ }
}
diff --git a/native/crates/app/src/brackets/edits.rs b/native/crates/app/src/brackets/edits.rs
new file mode 100644
index 00000000000..93a975e6ed7
--- /dev/null
+++ b/native/crates/app/src/brackets/edits.rs
@@ -0,0 +1,177 @@
+//! beforeEditPositionMapper.ts and combineTextEditInfos.ts: the edits between the bracket tree's parses and the
+//! offsets before them.
+
+use std::collections::VecDeque;
+
+use super::length::Length;
+
+/// `TextEditInfo`: the text from `start` to `end` (offsets before the edit) replaced by text of `new_length`.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct TextEditInfo {
+ pub start: Length,
+ pub end: Length,
+ pub new_length: Length,
+}
+
+/// `BeforeEditPositionMapper`: maps increasing offsets after edits, sorted and disjoint, to offsets before them.
+pub struct BeforeEditPositionMapper<'a> {
+ edits: &'a [TextEditInfo],
+ next_edit: usize,
+ delta_lines: isize,
+ delta_columns: isize,
+ /// The line, before the edits, whose columns `delta_columns` shifts.
+ delta_line_in_old: Option<usize>,
+}
+
+impl<'a> BeforeEditPositionMapper<'a> {
+ pub fn new(edits: &'a [TextEditInfo]) -> Self {
+ BeforeEditPositionMapper { edits, next_edit: 0, delta_lines: 0, delta_columns: 0, delta_line_in_old: None }
+ }
+
+ pub fn offset_before_change(&mut self, offset: Length) -> Length {
+ self.adjust_next_edit(offset);
+ self.current_to_old(offset)
+ }
+
+ /// The length from `offset` to the next edit, none after the last one.
+ pub fn distance_to_next_change(&mut self, offset: Length) -> Option<Length> {
+ self.adjust_next_edit(offset);
+ let next = self.edits.get(self.next_edit)?;
+ Some(offset.until(self.old_to_current(next.start)))
+ }
+
+ fn old_to_current(&self, old: Length) -> Length {
+ let lines = shift(old.lines, self.delta_lines);
+ match self.delta_line_in_old == Some(old.lines) {
+ true => Length::new(lines, shift(old.columns, self.delta_columns)),
+ false => Length::new(lines, old.columns),
+ }
+ }
+
+ fn current_to_old(&self, current: Length) -> Length {
+ let lines = shift(current.lines, -self.delta_lines);
+ match self.delta_line_in_old == Some(lines) {
+ true => Length::new(lines, shift(current.columns, -self.delta_columns)),
+ false => Length::new(lines, current.columns),
+ }
+ }
+
+ fn adjust_next_edit(&mut self, offset: Length) {
+ while let Some(edit) = self.edits.get(self.next_edit) {
+ let end_after = self.old_to_current(edit.start + edit.new_length);
+ if end_after > offset {
+ break;
+ }
+ self.next_edit += 1;
+ let end_before = self.old_to_current(edit.end);
+ self.delta_lines += end_after.lines as isize - end_before.lines as isize;
+ let previous_columns = if self.delta_line_in_old == Some(edit.end.lines) { self.delta_columns } else { 0 };
+ self.delta_columns = previous_columns + end_after.columns as isize - end_before.columns as isize;
+ self.delta_line_in_old = Some(edit.end.lines);
+ }
+ }
+}
+
+fn shift(value: usize, delta: isize) -> usize {
+ value.checked_add_signed(delta).expect("an edit shifts no offset before the document start")
+}
+
+/// `combineTextEditInfos`: the edits from the text before `first` to the text after `second`.
+pub fn combine_text_edit_infos(first: &[TextEditInfo], second: &[TextEditInfo]) -> Vec<TextEditInfo> {
+ if first.is_empty() {
+ return second.to_vec();
+ }
+ if second.is_empty() {
+ return first.to_vec();
+ }
+ let mut s0_to_s1 = Mappings { queue: length_mappings(first).into(), current: None };
+ s0_to_s1.current = s0_to_s1.queue.pop_front();
+ let mut result: Vec<TextEditInfo> = Vec::new();
+ let mut push_edit = |start: Length, end: Length, new_length: Length| match result.last_mut() {
+ Some(last) if last.end == start => *last = TextEditInfo { start: last.start, end, new_length: last.new_length + new_length },
+ _ => result.push(TextEditInfo { start, end, new_length }),
+ };
+ let mut s0_offset = Length::ZERO;
+ // The last step copies what is left of the first edits.
+ for s1_to_s2 in length_mappings(second).into_iter().map(Some).chain([None]) {
+ let s0_items = s0_to_s1.take(s1_to_s2.map(|mapping| mapping.before));
+ if let Some(mapping) = s1_to_s2.filter(|mapping| mapping.modified) {
+ let s0_end = s0_offset + s0_items.iter().fold(Length::ZERO, |sum, item| sum + item.before);
+ push_edit(s0_offset, s0_end, mapping.after);
+ s0_offset = s0_end;
+ continue;
+ }
+ for item in s0_items {
+ let start = s0_offset;
+ s0_offset = s0_offset + item.before;
+ if item.modified {
+ push_edit(start, s0_offset, item.after);
+ }
+ }
+ }
+ result
+}
+
+#[derive(Clone, Copy)]
+struct LengthMapping {
+ modified: bool,
+ before: Length,
+ after: Length,
+}
+
+impl LengthMapping {
+ fn split_at(self, after: Length) -> (LengthMapping, Option<LengthMapping>) {
+ let remaining = after.until(self.after);
+ if remaining.is_zero() {
+ return (self, None);
+ }
+ match self.modified {
+ true => (LengthMapping { after, ..self }, Some(LengthMapping { modified: true, before: Length::ZERO, after: remaining })),
+ false => (LengthMapping { modified: false, before: after, after }, Some(LengthMapping { modified: false, before: remaining, after: remaining })),
+ }
+ }
+}
+
+struct Mappings {
+ queue: VecDeque<LengthMapping>,
+ current: Option<LengthMapping>,
+}
+
+impl Mappings {
+ /// `nextS0ToS1MapWithS1LengthOf`: the mappings covering the next `s1_length` after them, all the rest for none.
+ fn take(&mut self, s1_length: Option<Length>) -> Vec<LengthMapping> {
+ let Some(mut s1_length) = s1_length else {
+ return self.current.take().into_iter().chain(self.queue.drain(..)).collect();
+ };
+ let mut result = Vec::new();
+ while let Some(current) = self.current
+ && !s1_length.is_zero()
+ {
+ let (item, remaining) = current.split_at(s1_length);
+ result.push(item);
+ s1_length = item.after.until(s1_length);
+ self.current = remaining.or_else(|| self.queue.pop_front());
+ }
+ if !s1_length.is_zero() {
+ result.push(LengthMapping { modified: false, before: s1_length, after: s1_length });
+ }
+ result
+ }
+}
+
+fn length_mappings(edits: &[TextEditInfo]) -> Vec<LengthMapping> {
+ let mut result = Vec::new();
+ let mut last_offset = Length::ZERO;
+ for edit in edits {
+ let space = last_offset.until(edit.start);
+ if !space.is_zero() {
+ result.push(LengthMapping { modified: false, before: space, after: space });
+ }
+ result.push(LengthMapping { modified: true, before: edit.start.until(edit.end), after: edit.new_length });
+ last_offset = edit.end;
+ }
+ result
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/native/crates/app/src/brackets/edits/tests.rs b/native/crates/app/src/brackets/edits/tests.rs
new file mode 100644
index 00000000000..07978d6ba4b
--- /dev/null
+++ b/native/crates/app/src/brackets/edits/tests.rs
@@ -0,0 +1,292 @@
+use super::*;
+
+fn length_of_string(text: &str) -> Length {
+ let lines = text.matches('\n').count();
+ Length::new(lines, text.rsplit('\n').next().expect("split yields a part").chars().count())
+}
+
+fn edit(start: (usize, usize), end: (usize, usize), text: &str) -> (TextEditInfo, String) {
+ (TextEditInfo { start: Length::new(start.0, start.1), end: Length::new(end.0, end.1), new_length: length_of_string(text) }, text.to_string())
+}
+
+/// `applyLineColumnEdits` over chars.
+fn apply(text: &str, edits: &[(TextEditInfo, String)]) -> String {
+ let mut chars: Vec<char> = text.chars().collect();
+ let mut line_starts = vec![0];
+ for (index, c) in chars.iter().enumerate() {
+ if *c == '\n' {
+ line_starts.push(index + 1);
+ }
+ }
+ let offset = |at: Length| line_starts[at.lines] + at.columns;
+ let mut edits: Vec<_> = edits.iter().map(|(edit, text)| (offset(edit.start), offset(edit.end), text)).collect();
+ edits.sort_by_key(|&(start, ..)| std::cmp::Reverse(start));
+ for (start, end, text) in edits {
+ chars.splice(start..end, text.chars());
+ }
+ chars.into_iter().collect()
+}
+
+/// beforeEditPositionMapper.test.ts `compute`: each new line, then the old line and column of each position in it,
+/// then the line and column count to the next change.
+fn compute(input: &[&str], edits: &[(TextEditInfo, String)]) -> Vec<String> {
+ let new_text = apply(&input.join("\n"), edits);
+ let infos: Vec<_> = edits.iter().map(|(edit, _)| *edit).collect();
+ let mut mapper = BeforeEditPositionMapper::new(&infos);
+ let pad = |text: String| format!("{text:<3}");
+ let mut result = Vec::new();
+ for (line_index, line) in new_text.split('\n').enumerate() {
+ let chars: Vec<char> = line.chars().collect();
+ let mut rows = [String::new(), String::new(), String::new(), String::new(), String::new()];
+ for column in 0..=chars.len() {
+ let before = mapper.offset_before_change(Length::new(line_index, column));
+ if column < chars.len() {
+ rows[0] += &pad(chars[column].to_string());
+ }
+ rows[1] += &pad(before.lines.to_string());
+ rows[2] += &pad(before.columns.to_string());
+ let distance = mapper.distance_to_next_change(Length::new(line_index, column));
+ rows[3] += &pad(distance.map_or("∞".into(), |distance| distance.lines.to_string()));
+ rows[4] += &pad(distance.map_or("∞".into(), |distance| distance.columns.to_string()));
+ }
+ result.extend(rows);
+ }
+ result
+}
+
+#[test]
+fn single_line_1() {
+ assert_eq!(
+ compute(&["0123456789"], &[edit((0, 4), (0, 7), "xy")]),
+ ["0 1 2 3 x y 7 8 9 ", "0 0 0 0 0 0 0 0 0 0 ", "0 1 2 3 4 5 7 8 9 10 ", "0 0 0 0 0 0 ∞ ∞ ∞ ∞ ", "4 3 2 1 0 0 ∞ ∞ ∞ ∞ "]
+ );
+}
+
+#[test]
+fn single_line_2() {
+ assert_eq!(
+ compute(&["0123456789"], &[edit((0, 2), (0, 4), "xxxx"), edit((0, 6), (0, 6), "yy")]),
+ [
+ "0 1 x x x x 4 5 y y 6 7 8 9 ",
+ "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ",
+ "0 1 2 3 4 5 4 5 6 7 6 7 8 9 10 ",
+ "0 0 0 0 0 0 0 0 0 0 ∞ ∞ ∞ ∞ ∞ ",
+ "2 1 0 0 0 0 2 1 0 0 ∞ ∞ ∞ ∞ ∞ ",
+ ]
+ );
+}
+
+const UNTOUCHED_SUPERSCRIPTS: [&str; 5] = ["⁰ ¹ ² ³ ⁴ ⁵ ⁶ ⁷ ⁸ ⁹ ", "2 2 2 2 2 2 2 2 2 2 2 ", "0 1 2 3 4 5 6 7 8 9 10 ", "∞ ∞ ∞ ∞ ∞ ∞ ∞ ∞ ∞ ∞ ∞ ", "∞ ∞ ∞ ∞ ∞ ∞ ∞ ∞ ∞ ∞ ∞ "];
+
+#[test]
+fn multi_line_replace_1() {
+ let mut expected = vec![
+ "₀ ₁ ₂ x y 3 4 5 6 7 8 9 ",
+ "0 0 0 0 0 1 1 1 1 1 1 1 1 ",
+ "0 1 2 3 4 3 4 5 6 7 8 9 10 ",
+ "0 0 0 0 0 ∞ ∞ ∞ ∞ ∞ ∞ ∞ ∞ ",
+ "3 2 1 0 0 ∞ ∞ ∞ ∞ ∞ ∞ ∞ ∞ ",
+ ];
+ expected.extend(UNTOUCHED_SUPERSCRIPTS);
+ assert_eq!(compute(&["₀₁₂₃₄₅₆₇₈₉", "0123456789", "⁰¹²³⁴⁵⁶⁷⁸⁹"], &[edit((0, 3), (1, 3), "xy")]), expected);
+}
+
+#[test]
+fn multi_line_replace_2() {
+ let mut expected = vec![
+ "₀ ₁ ₂ a b 0 1 2 3 4 c 7 8 ",
+ "0 0 0 0 0 1 1 1 1 1 1 1 1 1 ",
+ "0 1 2 3 4 0 1 2 3 4 5 7 8 9 ",
+ "0 0 0 0 0 0 0 0 0 0 0 ∞ ∞ ∞ ",
+ "3 2 1 0 0 5 4 3 2 1 0 ∞ ∞ ∞ ",
+ ];
+ expected.extend(UNTOUCHED_SUPERSCRIPTS);
+ assert_eq!(compute(&["₀₁₂₃₄₅₆₇₈₉", "012345678", "⁰¹²³⁴⁵⁶⁷⁸⁹"], &[edit((0, 3), (1, 0), "ab"), edit((1, 5), (1, 7), "c")]), expected);
+}
+
+#[test]
+fn multi_line_replace_3() {
+ assert_eq!(
+ compute(&["₀₁₂₃₄₅₆₇₈₉", "012345678", "⁰¹²³⁴⁵⁶⁷⁸⁹"], &[edit((0, 3), (1, 0), "ab"), edit((1, 5), (1, 7), "c"), edit((1, 8), (2, 4), "d")]),
+ [
+ "₀ ₁ ₂ a b 0 1 2 3 4 c 7 d ⁴ ⁵ ⁶ ⁷ ⁸ ⁹ ",
+ "0 0 0 0 0 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 ",
+ "0 1 2 3 4 0 1 2 3 4 5 7 8 4 5 6 7 8 9 10 ",
+ "0 0 0 0 0 0 0 0 0 0 0 0 0 ∞ ∞ ∞ ∞ ∞ ∞ ∞ ",
+ "3 2 1 0 0 5 4 3 2 1 0 1 0 ∞ ∞ ∞ ∞ ∞ ∞ ∞ ",
+ ]
+ );
+}
+
+#[test]
+fn multi_line_insert_1() {
+ assert_eq!(
+ compute(&["012345678"], &[edit((0, 3), (0, 5), "a\nb")]),
+ ["0 1 2 a ", "0 0 0 0 0 ", "0 1 2 3 4 ", "0 0 0 0 0 ", "3 2 1 0 0 ", "b 5 6 7 8 ", "1 0 0 0 0 0 ", "0 5 6 7 8 9 ", "0 ∞ ∞ ∞ ∞ ∞ ", "0 ∞ ∞ ∞ ∞ ∞ "]
+ );
+}
+
+#[test]
+fn multi_line_insert_2() {
+ assert_eq!(
+ compute(&["012345678"], &[edit((0, 3), (0, 5), "a\nb"), edit((0, 7), (0, 8), "x\ny")]),
+ [
+ "0 1 2 a ",
+ "0 0 0 0 0 ",
+ "0 1 2 3 4 ",
+ "0 0 0 0 0 ",
+ "3 2 1 0 0 ",
+ "b 5 6 x ",
+ "1 0 0 0 0 ",
+ "0 5 6 7 8 ",
+ "0 0 0 0 0 ",
+ "0 2 1 0 0 ",
+ "y 8 ",
+ "1 0 0 ",
+ "0 8 9 ",
+ "0 ∞ ∞ ",
+ "0 ∞ ∞ ",
+ ]
+ );
+}
+
+#[test]
+fn multi_line_replace_insert_1() {
+ let mut expected = vec![
+ "₀ ₁ ₂ a a a ",
+ "0 0 0 0 0 0 0 ",
+ "0 1 2 3 4 5 6 ",
+ "0 0 0 0 0 0 0 ",
+ "3 2 1 0 0 0 0 ",
+ "b b b 1 2 3 4 5 6 7 8 ",
+ "1 1 1 1 1 1 1 1 1 1 1 1 ",
+ "0 1 2 1 2 3 4 5 6 7 8 9 ",
+ "0 0 0 ∞ ∞ ∞ ∞ ∞ ∞ ∞ ∞ ∞ ",
+ "0 0 0 ∞ ∞ ∞ ∞ ∞ ∞ ∞ ∞ ∞ ",
+ ];
+ expected.extend(UNTOUCHED_SUPERSCRIPTS);
+ assert_eq!(compute(&["₀₁₂₃₄₅₆₇₈₉", "012345678", "⁰¹²³⁴⁵⁶⁷⁸⁹"], &[edit((0, 3), (1, 1), "aaa\nbbb")]), expected);
+}
+
+#[test]
+fn multi_line_replace_insert_2() {
+ assert_eq!(
+ compute(&["₀₁₂₃₄₅₆₇₈₉", "012345678", "⁰¹²³⁴⁵⁶⁷⁸⁹"], &[edit((0, 3), (1, 1), "aaa\nbbb"), edit((1, 5), (1, 5), "x\ny"), edit((1, 7), (2, 4), "k\nl")]),
+ [
+ "₀ ₁ ₂ a a a ",
+ "0 0 0 0 0 0 0 ",
+ "0 1 2 3 4 5 6 ",
+ "0 0 0 0 0 0 0 ",
+ "3 2 1 0 0 0 0 ",
+ "b b b 1 2 3 4 x ",
+ "1 1 1 1 1 1 1 1 1 ",
+ "0 1 2 1 2 3 4 5 6 ",
+ "0 0 0 0 0 0 0 0 0 ",
+ "0 0 0 4 3 2 1 0 0 ",
+ "y 5 6 k ",
+ "2 1 1 1 1 ",
+ "0 5 6 7 8 ",
+ "0 0 0 0 0 ",
+ "0 2 1 0 0 ",
+ "l ⁴ ⁵ ⁶ ⁷ ⁸ ⁹ ",
+ "2 2 2 2 2 2 2 2 ",
+ "0 4 5 6 7 8 9 10 ",
+ "0 ∞ ∞ ∞ ∞ ∞ ∞ ∞ ",
+ "0 ∞ ∞ ∞ ∞ ∞ ∞ ∞ ",
+ ]
+ );
+}
+
+/// A text model enough for combineTextEditInfos.test.ts: char offsets and positions over a string.
+struct Model(Vec<char>);
+
+impl Model {
+ fn position_at(&self, offset: usize) -> Length {
+ let before = &self.0[..offset];
+ match before.iter().rposition(|c| *c == '\n') {
+ Some(newline) => Length::new(before.iter().filter(|c| **c == '\n').count(), offset - newline - 1),
+ None => Length::new(0, offset),
+ }
+ }
+
+ fn offset_at(&self, position: Length) -> usize {
+ let line_start = match position.lines {
+ 0 => 0,
+ lines => self.0.iter().enumerate().filter(|(_, c)| **c == '\n').nth(lines - 1).expect("the line exists").0 + 1,
+ };
+ line_start + position.columns
+ }
+
+ fn value_in(&self, start: Length, end: Length) -> String {
+ self.0[self.offset_at(start)..self.offset_at(end)].iter().collect()
+ }
+
+ fn replace(&mut self, start: Length, end: Length, text: &str) {
+ let range = self.offset_at(start)..self.offset_at(end);
+ self.0.splice(range, text.chars());
+ }
+
+ /// The edits apply to the text before all of them, so they replace from the last one.
+ fn apply(&mut self, edits: &[TextEditInfo]) {
+ for edit in edits.iter().rev() {
+ self.replace(edit.start, edit.end, &new_text(edit.new_length));
+ }
+ }
+}
+
+fn new_text(length: Length) -> String {
+ "LLL\n".repeat(length.lines) + &"C".repeat(length.columns)
+}
+
+/// xorshift in place of upstream's `Random`: the cases differ, the property checked is the same.
+struct Random(u64);
+
+impl Random {
+ fn next_int_range(&mut self, start: usize, end: usize) -> usize {
+ self.0 ^= self.0 << 13;
+ self.0 ^= self.0 >> 7;
+ self.0 ^= self.0 << 17;
+ if end <= start {
+ return start;
+ }
+ start + (self.0 % (end - start) as u64) as usize
+ }
+}
+
+/// combineTextEditInfos.test.ts `getRandomEditInfos`.
+fn random_edits(model: &Model, count: usize, random: &mut Random) -> Vec<TextEditInfo> {
+ let mut edits = Vec::new();
+ let mut from = 0;
+ for _ in 0..count {
+ let start = random.next_int_range(from, model.0.len());
+ let end = random.next_int_range(start, model.0.len());
+ let new_length = Length::new(random.next_int_range(0, 3), random.next_int_range(0, 5));
+ let edit = TextEditInfo { start: model.position_at(start), end: model.position_at(end), new_length };
+ from = model.offset_at(edit.end);
+ edits.push(edit);
+ }
+ edits
+}
+
+/// combineTextEditInfos.test.ts: undoing the combined edits on the twice edited text gives the original back.
+#[test]
+fn combined_edits_map_the_text_before_both_to_the_text_after_both() {
+ for seed in 0..50 {
+ let mut random = Random(seed * 2654435761 + 1);
+ let s0 = Model("abcde\nfghij\nklmno\npqrst\n".chars().collect());
+ let edits1 = random_edits(&s0, random.next_int_range(1, 4), &mut random);
+ let mut s1 = Model(s0.0.clone());
+ s1.apply(&edits1);
+ let edits2 = random_edits(&s1, random.next_int_range(1, 4), &mut random);
+ let mut s2 = Model(s1.0.clone());
+ s2.apply(&edits2);
+
+ for edit in combine_text_edit_infos(&edits1, &edits2) {
+ let end = edit.start + edit.new_length;
+ let value = s2.value_in(edit.start, end);
+ assert!(value.chars().all(|c| matches!(c, 'L' | 'C' | '\n')), "seed {seed}: invalid edit {edit:?} over {value:?}");
+ s2.replace(edit.start, end, &s0.value_in(edit.start, edit.end));
+ }
+ assert_eq!(s2.0, s0.0, "seed {seed}");
+ }
+}
diff --git a/native/crates/app/src/brackets/ids.rs b/native/crates/app/src/brackets/ids.rs
new file mode 100644
index 00000000000..3c09e30e1bd
--- /dev/null
+++ b/native/crates/app/src/brackets/ids.rs
@@ -0,0 +1,92 @@
+//! smallImmutableSet.ts: a set of opening bracket ids as bits, keyed by one `DenseKeyProvider` for all languages.
+
+use std::collections::HashMap;
+use std::sync::{Mutex, OnceLock};
+
+/// `DenseKeyProvider.getKey`: the bit of a `languageId:::text` bracket id, the same for the whole process.
+pub fn key(id: &str) -> usize {
+ static KEYS: OnceLock<Mutex<HashMap<String, usize>>> = OnceLock::new();
+ let mut keys = KEYS.get_or_init(Mutex::default).lock().expect("no key lookup panics");
+ let next = keys.len();
+ *keys.entry(id.to_string()).or_insert(next)
+}
+
+/// Without trailing zero words, so equal sets compare equal.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct BracketIds(Vec<u64>);
+
+impl BracketIds {
+ pub const EMPTY: BracketIds = BracketIds(Vec::new());
+
+ pub fn of(ids: &[String]) -> Self {
+ let mut set = BracketIds::default();
+ for id in ids {
+ set = set.add(key(id));
+ }
+ set
+ }
+
+ pub fn add(mut self, key: usize) -> Self {
+ let word = key / 64;
+ if self.0.len() <= word {
+ self.0.resize(word + 1, 0);
+ }
+ self.0[word] |= 1 << (key % 64);
+ self
+ }
+
+ pub fn has(&self, key: usize) -> bool {
+ self.0.get(key / 64).is_some_and(|word| word & (1 << (key % 64)) != 0)
+ }
+
+ pub fn merge(&self, other: &BracketIds) -> BracketIds {
+ let (longer, shorter) = if self.0.len() >= other.0.len() { (self, other) } else { (other, self) };
+ let mut merged = longer.clone();
+ for (word, other) in merged.0.iter_mut().zip(&shorter.0) {
+ *word |= other;
+ }
+ merged
+ }
+
+ pub fn intersects(&self, other: &BracketIds) -> bool {
+ self.0.iter().zip(&other.0).any(|(a, b)| a & b != 0)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// smallImmutableSet.test.ts "Basic".
+ #[test]
+ fn sets_of_the_same_ids_are_equal_whatever_the_order() {
+ let empty = BracketIds::default();
+ let items1 = empty.clone().add(key("set test:::item1"));
+ let items12 = items1.clone().add(key("set test:::item2"));
+ let items2 = empty.clone().add(key("set test:::item2"));
+ let items21 = items2.clone().add(key("set test:::item1"));
+ let items3 = empty.add(key("set test:::item3"));
+
+ assert!(items12.intersects(&items1));
+ assert!(items12.has(key("set test:::item1")));
+ assert!(!items12.intersects(&items3));
+ assert!(!items12.has(key("set test:::item3")));
+ assert_eq!(items21, items12);
+ assert_ne!(items21, items2);
+ }
+
+ /// smallImmutableSet.test.ts "Many Elements".
+ #[test]
+ fn a_set_holds_more_ids_than_one_word() {
+ let mut set = BracketIds::default();
+ for i in 0..100 {
+ let key = key(&format!("many test:::item{i}"));
+ if i % 2 == 0 {
+ set = set.add(key);
+ }
+ }
+ for i in 0..100 {
+ assert_eq!(set.has(key(&format!("many test:::item{i}"))), i % 2 == 0);
+ }
+ }
+}
diff --git a/native/crates/app/src/brackets/length.rs b/native/crates/app/src/brackets/length.rs
new file mode 100644
index 00000000000..87174421c18
--- /dev/null
+++ b/native/crates/app/src/brackets/length.rs
@@ -0,0 +1,64 @@
+//! length.ts: a length in a document, or an offset from its start, as a line count and the column count (bytes)
+//! of the last line.
+
+use std::ops::Add;
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
+pub struct Length {
+ pub lines: usize,
+ pub columns: usize,
+}
+
+impl Length {
+ pub const ZERO: Length = Length { lines: 0, columns: 0 };
+
+ pub fn new(lines: usize, columns: usize) -> Self {
+ Length { lines, columns }
+ }
+
+ pub fn is_zero(self) -> bool {
+ self == Length::ZERO
+ }
+
+ /// `lengthDiffNonNegative`: the length from `self` to `end`, zero when `end` is not after `self`.
+ pub fn until(self, end: Length) -> Length {
+ if end <= self {
+ Length::ZERO
+ } else if self.lines == end.lines {
+ Length::new(0, end.columns - self.columns)
+ } else {
+ Length::new(end.lines - self.lines, end.columns)
+ }
+ }
+}
+
+/// `lengthAdd`: a length with lines restarts the column count.
+impl Add for Length {
+ type Output = Length;
+
+ fn add(self, other: Length) -> Length {
+ if other.lines == 0 { Length::new(self.lines, self.columns + other.columns) } else { Length::new(self.lines + other.lines, other.columns) }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// length.test.ts "Basic".
+ #[test]
+ fn adding_a_length_with_lines_restarts_the_columns() {
+ let l1 = Length::new(100, 10);
+ assert_eq!(l1 + Length::new(100, 10), Length::new(200, 10));
+ assert_eq!(l1 + Length::new(0, 10), Length::new(100, 20));
+ }
+
+ /// length.test.ts "lengthDiffNonNeg".
+ #[test]
+ fn the_length_until_an_earlier_offset_is_zero() {
+ assert_eq!(Length::new(100, 10).until(Length::new(100, 20)), Length::new(0, 10));
+ assert_eq!(Length::new(100, 10).until(Length::new(101, 20)), Length::new(1, 20));
+ assert_eq!(Length::new(101, 30).until(Length::new(101, 20)), Length::ZERO);
+ assert_eq!(Length::new(102, 10).until(Length::new(101, 20)), Length::ZERO);
+ }
+}
diff --git a/native/crates/app/src/brackets/tree.rs b/native/crates/app/src/brackets/tree.rs
new file mode 100644
index 00000000000..6f45071ed31
--- /dev/null
+++ b/native/crates/app/src/brackets/tree.rs
@@ -0,0 +1,513 @@
+//! ast.ts, concat23Trees.ts, nodeReader.ts, tokenizer.ts and parser.ts: the bracket pairs of a document as a
+//! (2,3) tree, which the parse after an edit builds from the unchanged nodes of the tree before it.
+
+use std::sync::Arc;
+
+use super::edits::{BeforeEditPositionMapper, TextEditInfo};
+use super::ids::BracketIds;
+use super::length::Length;
+use super::{BracketToken, LineBracket};
+
+/// `AstNode`, immutable: a parse shares the nodes it reuses with the tree before it.
+pub enum Node {
+ Text(Length),
+ Bracket { length: Length, token: Arc<BracketToken> },
+ /// `InvalidBracketAstNode`: a closing bracket that closes none of the brackets open around it.
+ Unexpected { length: Length, closes: BracketIds },
+ /// `PairAstNode`: `missing` are the opening brackets the closing brackets inside it lack.
+ Pair { length: Length, open: Arc<Node>, child: Option<Arc<Node>>, close: Option<Arc<Node>>, missing: BracketIds },
+ List { length: Length, height: usize, children: Vec<Arc<Node>>, missing: BracketIds },
+}
+
+impl Node {
+ pub fn length(&self) -> Length {
+ match self {
+ Node::Text(length) => *length,
+ Node::Bracket { length, .. } | Node::Unexpected { length, .. } | Node::Pair { length, .. } | Node::List { length, .. } => *length,
+ }
+ }
+
+ /// `listHeight`.
+ fn height(&self) -> usize {
+ match self {
+ Node::List { height, .. } => *height,
+ _ => 0,
+ }
+ }
+
+ /// `missingOpeningBracketIds`.
+ fn missing(&self) -> &BracketIds {
+ static NONE: BracketIds = BracketIds::EMPTY;
+ match self {
+ Node::Text(_) | Node::Bracket { .. } => &NONE,
+ Node::Unexpected { closes, .. } => closes,
+ Node::Pair { missing, .. } | Node::List { missing, .. } => missing,
+ }
+ }
+
+ /// `childrenLength`: a pair has three, the middle and the last of them maybe none.
+ fn child_count(&self) -> usize {
+ match self {
+ Node::Pair { .. } => 3,
+ Node::List { children, .. } => children.len(),
+ _ => 0,
+ }
+ }
+
+ fn child(&self, index: usize) -> Option<&Arc<Node>> {
+ match self {
+ Node::Pair { open, child, close, .. } => [Some(open), child.as_ref(), close.as_ref()][index],
+ Node::List { children, .. } => children.get(index),
+ _ => None,
+ }
+ }
+
+ pub fn children(&self) -> impl Iterator<Item = &Arc<Node>> {
+ (0..self.child_count()).filter_map(|index| self.child(index))
+ }
+
+ /// `canBeReused` inside the opening brackets `opened`.
+ fn can_be_reused(&self, opened: &BracketIds) -> bool {
+ match self {
+ Node::Text(_) => true,
+ Node::Bracket { .. } => false,
+ Node::Unexpected { closes, .. } => !opened.intersects(closes),
+ Node::Pair { close, missing, .. } => close.is_some() && !opened.intersects(missing),
+ Node::List { children, missing, .. } => {
+ if opened.intersects(missing) || children.is_empty() {
+ return false;
+ }
+ let mut last = self;
+ while let Node::List { children, .. } = last {
+ last = children.last().expect("a list in a tree holds children");
+ }
+ last.can_be_reused(opened)
+ }
+ }
+ }
+}
+
+/// `PairAstNode.create`.
+fn pair(open: Arc<Node>, child: Option<Arc<Node>>, close: Option<Arc<Node>>) -> Arc<Node> {
+ let mut length = open.length();
+ for part in child.iter().chain(&close) {
+ length = length + part.length();
+ }
+ let missing = child.as_ref().map_or(BracketIds::EMPTY, |child| child.missing().clone());
+ Arc::new(Node::Pair { length, open, child, close, missing })
+}
+
+/// `ListAstNode.create` and `create23`: children of one height.
+pub fn list(children: Vec<Arc<Node>>) -> Arc<Node> {
+ let mut length = Length::ZERO;
+ let mut missing = BracketIds::EMPTY;
+ for child in &children {
+ length = length + child.length();
+ missing = missing.merge(child.missing());
+ }
+ let height = children.first().map_or(0, |first| first.height() + 1);
+ Arc::new(Node::List { length, height, children, missing })
+}
+
+/// `concat23Trees`: the items in order in one balanced tree, whatever their heights.
+pub fn concat23_trees(items: Vec<Arc<Node>>) -> Option<Arc<Node>> {
+ let mut runs = Vec::new();
+ let mut items = items.into_iter().peekable();
+ while let Some(first) = items.next() {
+ let mut run = vec![first];
+ while let Some(item) = items.next_if(|item| item.height() == run[0].height()) {
+ run.push(item);
+ }
+ runs.extend(concat23_trees_of_same_height(run));
+ }
+ let mut runs = runs.into_iter();
+ let mut first = runs.next()?;
+ let Some(mut second) = runs.next() else { return Some(first) };
+ for item in runs {
+ if first.height().abs_diff(second.height()) <= second.height().abs_diff(item.height()) {
+ first = concat(&first, second);
+ second = item;
+ } else {
+ second = concat(&second, item);
+ }
+ }
+ Some(concat(&first, second))
+}
+
+/// `concat23TreesOfSameHeight`: pairs of items, the last three together when odd, until three or fewer are left.
+pub fn concat23_trees_of_same_height(mut items: Vec<Arc<Node>>) -> Option<Arc<Node>> {
+ if items.len() <= 1 {
+ return items.pop();
+ }
+ while items.len() > 3 {
+ let count = items.len();
+ let mut parents = Vec::with_capacity(count / 2);
+ let mut items_left = items.into_iter();
+ for index in 0..count / 2 {
+ let third = if 2 * index + 3 == count { 3 } else { 2 };
+ parents.push(list(items_left.by_ref().take(third).collect()));
+ }
+ items = parents;
+ }
+ Some(list(items))
+}
+
+fn concat(first: &Arc<Node>, second: Arc<Node>) -> Arc<Node> {
+ if first.height() == second.height() {
+ list(vec![first.clone(), second])
+ } else if first.height() > second.height() {
+ match insert(first, second, End::Last) {
+ (list, None) => list,
+ (list, Some(sibling)) => self::list(vec![list, sibling]),
+ }
+ } else {
+ match insert(&second, first.clone(), End::First) {
+ (list, None) => list,
+ (list, Some(sibling)) => self::list(vec![sibling, list]),
+ }
+ }
+}
+
+#[derive(Clone, Copy)]
+enum End {
+ First,
+ Last,
+}
+
+/// `append` and `prepend`: `node` added at `end` of `list` among the nodes of its height, and the sibling of `list`
+/// split off from it when its level there was full.
+fn insert(list: &Arc<Node>, node: Arc<Node>, end: End) -> (Arc<Node>, Option<Arc<Node>>) {
+ let Node::List { children, height, .. } = &**list else { unreachable!("only a list is higher than another node") };
+ let mut children = children.clone();
+ let edge = match end {
+ End::First => 0,
+ End::Last => children.len() - 1,
+ };
+ let node = if *height == node.height() + 1 {
+ Some(node)
+ } else {
+ let (child, sibling) = insert(&children[edge], node, end);
+ children[edge] = child;
+ sibling
+ };
+ let Some(node) = node else { return (self::list(children), None) };
+ if children.len() < 3 {
+ match end {
+ End::First => children.insert(0, node),
+ End::Last => children.push(node),
+ }
+ return (self::list(children), None);
+ }
+ let sibling = match end {
+ End::First => self::list(vec![node, children.remove(0)]),
+ End::Last => self::list(vec![children.pop().expect("a full list"), node]),
+ };
+ (self::list(children), Some(sibling))
+}
+
+/// `NodeReader`: the nodes of a tree at increasing offsets.
+struct NodeReader {
+ next_nodes: Vec<Arc<Node>>,
+ offsets: Vec<Length>,
+ indexes: Vec<usize>,
+ last_offset: Length,
+}
+
+impl NodeReader {
+ fn new(root: Arc<Node>) -> Self {
+ NodeReader { next_nodes: vec![root], offsets: vec![Length::ZERO], indexes: Vec::new(), last_offset: Length::ZERO }
+ }
+
+ /// `readLongestNodeAt`: the longest node starting at `offset` that `predicate` accepts.
+ fn read_longest_node_at(&mut self, offset: Length, predicate: impl Fn(&Node) -> bool) -> Option<Arc<Node>> {
+ assert!(offset >= self.last_offset, "the reader reads at increasing offsets");
+ self.last_offset = offset;
+ loop {
+ let node = self.next_nodes.last()?.clone();
+ let node_offset = *self.offsets.last().expect("an offset per node");
+ if offset < node_offset {
+ return None;
+ }
+ if node_offset < offset {
+ if node_offset + node.length() <= offset {
+ self.next_node_after_current();
+ } else {
+ match next_child_index(&node, None) {
+ Some(index) => self.push_child(&node, index, node_offset),
+ None => self.next_node_after_current(),
+ }
+ }
+ continue;
+ }
+ if predicate(&node) {
+ self.next_node_after_current();
+ return Some(node);
+ }
+ match next_child_index(&node, None) {
+ Some(index) => self.push_child(&node, index, node_offset),
+ None => {
+ self.next_node_after_current();
+ return None;
+ }
+ }
+ }
+ }
+
+ fn push_child(&mut self, node: &Arc<Node>, index: usize, offset: Length) {
+ self.next_nodes.push(node.child(index).expect("a present child").clone());
+ self.offsets.push(offset);
+ self.indexes.push(index);
+ }
+
+ fn next_node_after_current(&mut self) {
+ loop {
+ let (Some(node), Some(offset)) = (self.next_nodes.pop(), self.offsets.pop()) else { return };
+ let Some(&index) = self.indexes.last() else { return };
+ let parent = self.next_nodes.last().expect("a parent per index");
+ match next_child_index(parent, Some(index)) {
+ Some(next) => {
+ let child = parent.child(next).expect("a present child").clone();
+ self.next_nodes.push(child);
+ self.offsets.push(offset + node.length());
+ *self.indexes.last_mut().expect("checked above") = next;
+ return;
+ }
+ None => {
+ self.indexes.pop();
+ }
+ }
+ }
+ }
+}
+
+fn next_child_index(node: &Node, after: Option<usize>) -> Option<usize> {
+ let start = after.map_or(0, |after| after + 1);
+ (start..node.child_count()).find(|&index| node.child(index).is_some())
+}
+
+/// A token of `TextBufferTokenizer`: text, or a bracket.
+struct Token {
+ length: Length,
+ bracket: Option<Arc<BracketToken>>,
+}
+
+/// `TextBufferTokenizer` over each line's brackets, read from the tokens before.
+struct Tokenizer<'a> {
+ lines: &'a [&'a [LineBracket]],
+ lengths: &'a [usize],
+ offset: Length,
+ peeked: Option<Token>,
+}
+
+impl Tokenizer<'_> {
+ fn peek(&mut self) -> Option<&Token> {
+ if self.peeked.is_none() {
+ self.peeked = self.token_at_offset();
+ }
+ self.peeked.as_ref()
+ }
+
+ fn read(&mut self) -> Option<Token> {
+ let token = self.peeked.take().or_else(|| self.token_at_offset())?;
+ self.offset = self.offset + token.length;
+ Some(token)
+ }
+
+ fn skip(&mut self, length: Length) {
+ self.peeked = None;
+ self.offset = self.offset + length;
+ }
+
+ /// A bracket, or the text up to the next one: about 30 lines or 1500 bytes at most, so edits keep the text
+ /// around them (`lengthHeuristic`); the length of a split never changes the pairs.
+ fn token_at_offset(&self) -> Option<Token> {
+ let last = self.lengths.len().checked_sub(1)?;
+ let Length { lines: mut line, columns: mut column } = self.offset;
+ if line > last || (line == last && column >= self.lengths[last]) {
+ return None;
+ }
+ let next_bracket = |line: usize, column: usize| {
+ let brackets = self.lines[line];
+ brackets.get(brackets.partition_point(|bracket| bracket.range.start < column))
+ };
+ if let Some(bracket) = next_bracket(line, column).filter(|bracket| bracket.range.start == column) {
+ return Some(Token { length: Length::new(0, bracket.range.len()), bracket: Some(bracket.token.clone()) });
+ }
+ let mut heuristic = 0;
+ loop {
+ if let Some(bracket) = next_bracket(line, column) {
+ column = bracket.range.start;
+ break;
+ }
+ heuristic += self.lengths[line] - column;
+ column = self.lengths[line];
+ if line == last || heuristic > 1500 {
+ break;
+ }
+ line += 1;
+ column = 0;
+ heuristic += 33;
+ if heuristic > 1000 {
+ break;
+ }
+ }
+ Some(Token { length: self.offset.until(Length::new(line, column)), bracket: None })
+ }
+}
+
+/// `parseDocument`: the tree of the brackets of `lines` (each line's length in `lengths`), reusing the nodes of
+/// `previous` that `edits` since it left unchanged.
+pub fn parse_document(lines: &[&[LineBracket]], lengths: &[usize], edits: &[TextEditInfo], previous: Option<Arc<Node>>) -> Arc<Node> {
+ let mut parser = Parser {
+ tokenizer: Tokenizer { lines, lengths, offset: Length::ZERO, peeked: None },
+ reader: previous.map(NodeReader::new),
+ mapper: BeforeEditPositionMapper::new(edits),
+ };
+ parser.parse_list(&BracketIds::EMPTY, 0).unwrap_or_else(|| list(Vec::new()))
+}
+
+struct Parser<'a> {
+ tokenizer: Tokenizer<'a>,
+ reader: Option<NodeReader>,
+ mapper: BeforeEditPositionMapper<'a>,
+}
+
+impl Parser<'_> {
+ /// The nodes up to a closing bracket of `opened`.
+ fn parse_list(&mut self, opened: &BracketIds, level: usize) -> Option<Arc<Node>> {
+ let mut items = Vec::new();
+ loop {
+ let child = match self.child_from_previous_tree(opened) {
+ Some(child) => child,
+ None => {
+ let Some(token) = self.tokenizer.peek() else { break };
+ if token.bracket.as_ref().is_some_and(|bracket| !bracket.opening && bracket.ids.intersects(opened)) {
+ break;
+ }
+ self.parse_child(opened, level + 1)
+ }
+ };
+ if matches!(&*child, Node::List { children, .. } if children.is_empty()) {
+ continue;
+ }
+ items.push(child);
+ }
+ match self.reader {
+ Some(_) => concat23_trees(items),
+ None => concat23_trees_of_same_height(items),
+ }
+ }
+
+ /// `tryReadChildFromCache`: the longest node of the tree before at the offset that ends before the next edit.
+ fn child_from_previous_tree(&mut self, opened: &BracketIds) -> Option<Arc<Node>> {
+ let reader = self.reader.as_mut()?;
+ let max_length = self.mapper.distance_to_next_change(self.tokenizer.offset);
+ if max_length.is_some_and(Length::is_zero) {
+ return None;
+ }
+ let offset = self.mapper.offset_before_change(self.tokenizer.offset);
+ let node = reader.read_longest_node_at(offset, |node| max_length.is_none_or(|max| node.length() < max) && node.can_be_reused(opened))?;
+ self.tokenizer.skip(node.length());
+ Some(node)
+ }
+
+ fn parse_child(&mut self, opened: &BracketIds, level: usize) -> Arc<Node> {
+ let token = self.tokenizer.read().expect("parse_list peeked a token");
+ let Some(bracket) = token.bracket else { return Arc::new(Node::Text(token.length)) };
+ if !bracket.opening {
+ return Arc::new(Node::Unexpected { length: token.length, closes: bracket.ids.clone() });
+ }
+ if level > 300 {
+ return Arc::new(Node::Text(token.length));
+ }
+ let child = self.parse_list(&opened.merge(&bracket.ids), level + 1);
+ let closes = self.tokenizer.peek().and_then(|next| next.bracket.as_ref()).is_some_and(|next| !next.opening && next.ids.intersects(&bracket.ids));
+ let close = closes.then(|| self.tokenizer.read().expect("peeked")).map(|close| Arc::new(Node::Bracket { length: close.length, token: close.bracket.expect("a bracket") }));
+ pair(Arc::new(Node::Bracket { length: token.length, token: bracket }), child, close)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn text(columns: usize) -> Arc<Node> {
+ Arc::new(Node::Text(Length::new(1, columns)))
+ }
+
+ /// `flattenLists`: lists of lists as one list of the other nodes.
+ fn flatten(node: &Arc<Node>) -> Vec<Length> {
+ match &**node {
+ Node::List { children, .. } => children.iter().flat_map(flatten).collect(),
+ _ => vec![node.length()],
+ }
+ }
+
+ /// The (2,3) tree invariant: each list holds two or three children of one height.
+ fn assert_balanced(node: &Arc<Node>) {
+ if let Node::List { children, height, .. } = &**node {
+ assert!((2..=3).contains(&children.len()), "{} children", children.len());
+ for child in children {
+ assert_eq!(child.height() + 1, *height);
+ assert_balanced(child);
+ }
+ }
+ }
+
+ /// concat23Trees.test.ts `testMerge`: the merged tree holds the leaves of the lists in order.
+ fn test_merge(lists: Vec<Arc<Node>>) {
+ let expected: Vec<Length> = lists.iter().flat_map(flatten).collect();
+ let Some(merged) = concat23_trees(lists) else { return assert!(expected.is_empty()) };
+ assert_eq!(flatten(&merged), expected);
+ assert_balanced(&merged);
+ assert_eq!(merged.length(), expected.iter().fold(Length::ZERO, |sum, length| sum + *length));
+ }
+
+ /// Numbered leaves, so a merge out of order fails.
+ fn tree(height: usize, first: &mut usize) -> Arc<Node> {
+ if height == 0 {
+ *first += 1;
+ return text(*first);
+ }
+ list(vec![tree(height - 1, first), tree(height - 1, first)])
+ }
+
+ #[test]
+ fn empty_list() {
+ test_merge(Vec::new());
+ }
+
+ #[test]
+ fn same_height_lists() {
+ let mut leaf = 0;
+ test_merge((0..5).map(|_| tree(1, &mut leaf)).collect());
+ }
+
+ #[test]
+ fn different_height_lists_1() {
+ let mut leaf = 0;
+ test_merge(vec![tree(1, &mut leaf), tree(2, &mut leaf)]);
+ }
+
+ #[test]
+ fn different_height_lists_2() {
+ let mut leaf = 0;
+ test_merge(vec![tree(2, &mut leaf), tree(1, &mut leaf)]);
+ }
+
+ #[test]
+ fn different_height_lists_3() {
+ let mut leaf = 0;
+ test_merge(vec![tree(2, &mut leaf), tree(1, &mut leaf), tree(1, &mut leaf), tree(2, &mut leaf), tree(2, &mut leaf)]);
+ }
+
+ #[test]
+ fn appending_to_full_levels_splits_them() {
+ let mut leaf = 0;
+ let mut items = vec![tree(3, &mut leaf)];
+ items.extend((0..7).map(|_| tree(0, &mut leaf)));
+ items.push(tree(2, &mut leaf));
+ items.extend((0..5).map(|_| tree(0, &mut leaf)));
+ test_merge(items);
+ }
+}
diff --git a/native/crates/app/src/editor/bracket_matching.rs b/native/crates/app/src/editor/bracket_matching.rs
index fa2e6c6343f..154fba0979a 100644
--- a/native/crates/app/src/editor/bracket_matching.rs
+++ b/native/crates/app/src/editor/bracket_matching.rs
@@ -18,15 +18,15 @@ impl OpenEditor {
let position = selection.start();
let (line, offset) = byte_position(lines, position);
let target = match brackets.match_bracket(line, offset) {
- Some([open, close]) if contains(open, line, offset) && !contains(close, line, offset) => Some(close),
- Some([open, close]) if contains(close, line, offset) => Some(open),
+ Some([open, close]) if contains(&open, line, offset) && !contains(&close, line, offset) => Some(close),
+ Some([open, close]) if contains(&close, line, offset) => Some(open),
Some(_) => None,
None => match brackets.enclosing_brackets(line, offset) {
Some([_, close]) => Some(close),
None => brackets.next_bracket(line, offset),
},
};
- selections.push(Selection::caret(target.map_or(position, |bracket| start(lines, bracket))));
+ selections.push(Selection::caret(target.map_or(position, |bracket| start(lines, &bracket))));
}
drop(document);
self.set_selections(selections);
@@ -44,16 +44,16 @@ impl OpenEditor {
let (line, offset) = byte_position(lines, position);
let pair = brackets.match_bracket(line, offset).or_else(|| brackets.enclosing_brackets(line, offset)).or_else(|| {
let (next_line, next) = brackets.next_bracket(line, offset)?;
- brackets.match_bracket(*next_line, next.start)
+ brackets.match_bracket(next_line, next.start)
});
let Some(mut pair) = pair else { continue };
pair.sort_by_key(|(line, range)| (*line, range.start));
let [open, close] = pair;
let (mut from, mut to) = match select_brackets {
- true => (start(lines, open), end(lines, close)),
- false => (end(lines, open), start(lines, close)),
+ true => (start(lines, &open), end(lines, &close)),
+ false => (end(lines, &open), start(lines, &close)),
};
- if contains(close, line, offset) {
+ if contains(&close, line, offset) {
(from, to) = (to, from);
}
selections.push(Selection { anchor: from, head: to });
@@ -73,7 +73,7 @@ impl OpenEditor {
let lines = &document.lines;
let (line, offset) = byte_position(lines, position);
let Some([open, close]) = brackets.match_bracket(line, offset).or_else(|| brackets.enclosing_brackets(line, offset)) else { continue };
- let edits = [open, close].map(|bracket| (start(lines, bracket), end(lines, bracket), String::new(), false)).into();
+ let edits = [open, close].map(|bracket| (start(lines, &bracket), end(lines, &bracket), String::new(), false)).into();
drop(document);
self.push_undo_stop();
changes.extend(self.execute_edits(edits, None, EditReason::Unknown("editor.action.removeBrackets")));
diff --git a/native/crates/app/src/editor/mouse_selection.rs b/native/crates/app/src/editor/mouse_selection.rs
index 5a9b3c005e0..4b611febf00 100644
--- a/native/crates/app/src/editor/mouse_selection.rs
+++ b/native/crates/app/src/editor/mouse_selection.rs
@@ -90,7 +90,7 @@ impl OpenEditor {
let text = &lines[position.line];
let byte = |column: usize| text.char_indices().nth(column).map_or(text.len(), |(offset, _)| offset);
let at_byte = |line: usize, offset: usize| Position::new(line, lines[line][..offset].chars().count());
- let between = |[open, close]: [&BracketRange; 2]| Selection { anchor: at_byte(open.0, open.1.end), head: at_byte(close.0, close.1.start) };
+ let between = |[open, close]: [BracketRange; 2]| Selection { anchor: at_byte(open.0, open.1.end), head: at_byte(close.0, close.1.start) };
let offset = byte(position.column);
if position.column > 0
&& let Some(pair) = brackets.match_bracket(position.line, byte(position.column - 1))
diff --git a/native/crates/app/src/editor/smart_select.rs b/native/crates/app/src/editor/smart_select.rs
index a56c1220251..6f8463cfbab 100644
--- a/native/crates/app/src/editor/smart_select.rs
+++ b/native/crates/app/src/editor/smart_select.rs
@@ -95,7 +95,7 @@ impl OpenEditor {
let lines = &self.document().lines;
let brackets = match provided {
Some(_) => Vec::new(),
- None => self.document().tokens.pairs(languages, lines, &self.document().language_id).brackets,
+ None => self.document().tokens.pairs(languages, lines, &self.document().language_id).pair_brackets(),
};
let brackets = char_brackets(lines, &brackets);
let word_pattern = languages.rules(&self.document().language_id).and_then(|rules| rules.word_pattern.as_deref());
@@ -113,7 +113,7 @@ impl OpenEditor {
/// `BracketSelectionRangeProvider` alone at `position` (1-based column), inner first, as wordDistance.ts asks it.
pub fn bracket_selection_ranges(&self, languages: &Languages, position: Position) -> Vec<Span> {
let lines = &self.document().lines;
- let brackets = self.document().tokens.pairs(languages, lines, &self.document().language_id).brackets;
+ let brackets = self.document().tokens.pairs(languages, lines, &self.document().language_id).pair_brackets();
bracket_ranges(lines, &char_brackets(lines, &brackets), position)
}
}
diff --git a/native/crates/app/src/editor/smart_select/tests.rs b/native/crates/app/src/editor/smart_select/tests.rs
index 0f46f0266c0..e6224fe5ff0 100644
--- a/native/crates/app/src/editor/smart_select/tests.rs
+++ b/native/crates/app/src/editor/smart_select/tests.rs
@@ -27,7 +27,7 @@ fn word_pattern<'a>(editor: &OpenEditor, languages: &'a Languages) -> Option<&'a
}
fn brackets_of(editor: &OpenEditor, languages: &Languages) -> Vec<PairBracket> {
- editor.document().tokens.pairs(languages, &editor.document().lines, &editor.document().language_id).brackets
+ editor.document().tokens.pairs(languages, &editor.document().lines, &editor.document().language_id).pair_brackets()
}
/// `assertGetRangesToPosition`: `expected` lists the outermost range first.
diff --git a/native/crates/app/src/editor/word_wrap/tests.rs b/native/crates/app/src/editor/word_wrap/tests.rs
index 900c5c8ee76..787598d20be 100644
--- a/native/crates/app/src/editor/word_wrap/tests.rs
+++ b/native/crates/app/src/editor/word_wrap/tests.rs
@@ -420,7 +420,7 @@ fn bracket_pair_guides_skip_the_view_lines_past_a_wrap() {
let style = textmate::Style { font_style: 0, foreground: 1, background: 2 };
let span = |line: &String| Span { end: line.len(), language: "test", token_type: textmate::StandardTokenType::Other, balanced_brackets: true, style };
let spans: Vec<_> = lines.iter().map(|line| (line.as_str(), vec![span(line)])).collect();
- let pairs = DocumentBrackets::new(&spans, &languages).pairs;
+ let pairs = DocumentBrackets::new(&spans, &languages).pairs_in_lines(0..4);
let options = BracketGuideOptions { include_inactive: true, highlight_active: false, horizontal: HorizontalGuides::Enabled };
let guides = bracket_guides(&pairs, &lines, 4, 0..4, None, &options);
// "{aaa |bbbb |cccc", "x", "aa}a |bbbb |cccc", "(aaa |bbbb |ccc)".
diff --git a/native/crates/app/src/syntax.rs b/native/crates/app/src/syntax.rs
index e2f7fbb4720..f7608296355 100644
--- a/native/crates/app/src/syntax.rs
+++ b/native/crates/app/src/syntax.rs
@@ -9,7 +9,7 @@ use gpui::{FontStyle, FontWeight, HighlightStyle, Hsla, Rgba, StrikethroughStyle
use serde_json::{Map, Value, json};
use textmate::{Grammar, State, Token};
-use crate::brackets::{BracketGuide, BracketGuideOptions, BracketRange, DocumentBrackets, LineBracket, Span, line_brackets};
+use crate::brackets::{BracketCache, BracketGuide, BracketGuideOptions, BracketRange, DocumentBrackets, Span, line_brackets};
use crate::languages::Languages;
use crate::theme::{Theme, ThemeKind};
@@ -103,10 +103,9 @@ struct TokenStore {
tokens: Vec<Vec<Token>>,
end_states: Vec<Option<State>>,
invalid: InvalidLines,
- /// Each line's brackets under the drawing theme, and under the empty theme `pairs` reads, until its text or
- /// tokens change.
- brackets: Vec<Option<Vec<LineBracket>>>,
- plain_brackets: Vec<Option<Vec<LineBracket>>>,
+ /// 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)>,
@@ -119,8 +118,8 @@ impl TokenStore {
self.end_states = vec![None; line_count];
self.invalid = InvalidLines::default();
self.invalid.add_range(0..line_count);
- self.brackets = vec![None; line_count];
- self.plain_brackets = vec![None; line_count];
+ self.brackets = BracketCache::new(line_count);
+ self.plain_brackets = BracketCache::new(line_count);
self.viewport = None;
}
@@ -154,7 +153,7 @@ impl Tokenization {
let colors = bracket_colors(theme);
let unexpected = theme.color("editorBracketHighlight.unexpectedBracket.foreground").map(Hsla::from);
let mut colored = Vec::new();
- for bracket in &brackets.lines[index] {
+ 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 {
@@ -215,7 +214,7 @@ impl Tokenization {
previous = Some(style);
start = token.end;
}
- for bracket in &brackets.lines[index] {
+ for bracket in brackets.line(index) {
starts.extend([bracket.range.start, bracket.range.end]);
}
starts.retain(|&start| start < lines[index].len() || start == 0);
@@ -307,7 +306,8 @@ impl Tokenization {
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 pair = brackets.pairs.iter().rev().find(|pair| {
+ 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);
@@ -317,24 +317,17 @@ impl Tokenization {
}
/// The bracket pairs of the document in `language`, also without a grammar.
- // shortcut: pairs all lines' brackets per call, where upstream queries its incremental bracket tree.
pub fn pairs(&self, languages: &Languages, lines: &[String], language: &str) -> DocumentBrackets {
- if self.grammar.is_some() {
- return self.document_brackets(&textmate::Theme::new(&[]), languages, lines, true);
- }
- // nullTokenize: one Other token over each line, in the model's language.
- let style = textmate::Style { font_style: 0, foreground: 0, background: 0 };
- let spans: Vec<_> = lines.iter().map(|text| (text.as_str(), vec![Span { end: text.len(), language, token_type: textmate::StandardTokenType::Other, balanced_brackets: true, style }])).collect();
- DocumentBrackets::new(&spans, &languages.brackets)
+ self.document_brackets(&textmate::Theme::new(&[]), languages, lines, language, true)
}
/// `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, lines, tab_size, range, cursor, options);
+ 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, 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
@@ -344,18 +337,15 @@ impl Tokenization {
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);
- let owned = |[open, close]: [&BracketRange; 2]| [open.clone(), close.clone()];
match brackets.match_bracket(line, offset) {
- Some(pair) => Some((owned(pair), true)),
- None => brackets.enclosing_brackets(line, offset).map(|pair| (owned(pair), false)),
+ 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 pairs are dropped.
- // shortcut: pairs the brackets of all lines again (6.5 ms for 78k brackets), where upstream's BracketPairsTree reuses
- // the unchanged nodes; upgrade when the typing_latency_on_a_large_file gate fails on the pairing.
+ /// 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 = OnceCell::new();
let store = self.lines.get_mut();
@@ -366,8 +356,8 @@ impl Tokenization {
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.splice(start..=end, (0..new_line_count).map(|_| None));
- store.plain_brackets.splice(start..=end, (0..new_line_count).map(|_| None));
+ 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.
@@ -392,41 +382,45 @@ impl Tokenization {
/// The bracket pairs hold token styles of the theme they were paired under.
pub fn theme_changed(&mut self) {
self.brackets = OnceCell::new();
- self.lines.get_mut().brackets.fill(None);
+ let store = self.lines.get_mut();
+ store.brackets = BracketCache::new(store.tokens.len());
}
fn brackets(&self, theme: &Theme, languages: &Languages, lines: &[String]) -> &DocumentBrackets {
- self.brackets.get_or_init(|| self.document_brackets(&theme.tokens, languages, lines, false))
+ self.brackets.get_or_init(|| self.document_brackets(&theme.tokens, languages, lines, "", false))
}
/// 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.
- fn document_brackets(&self, theme: &textmate::Theme, languages: &Languages, lines: &[String], plain: bool) -> DocumentBrackets {
- self.tokenize_for(lines, Duration::MAX, BRACKET_TOKENIZE_LINES);
+ /// 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 store = &mut *store;
- let cache = if plain { &mut store.plain_brackets } else { &mut store.brackets };
- for ((text, tokens), brackets) in lines.iter().zip(&store.tokens).zip(cache.iter_mut()) {
- if brackets.is_some() {
- continue;
- }
- let spans: Vec<_> = tokens
- .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();
- *brackets = Some(line_brackets(text, &spans, &languages.brackets));
- }
- let found: Vec<_> = cache.iter().map(|brackets| brackets.as_deref().expect("every line's brackets were just read")).collect();
- let document_end = lines.last().map_or((0, 0), |text| (lines.len() - 1, text.len()));
- DocumentBrackets::from_lines(&found, document_end)
+ 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
@@ -460,8 +454,8 @@ impl Tokenization {
for line in first..=last {
let (tokens, end_state) = tokenize_text(grammar, lines, line, state.as_ref());
store.tokens[line] = tokens;
- store.brackets[line] = None;
- store.plain_brackets[line] = None;
+ store.brackets.lines[line] = None;
+ store.plain_brackets.lines[line] = None;
state = Some(end_state);
}
store.invalid.add_range(first..last + 1);
@@ -542,8 +536,8 @@ impl Tokenization {
};
let (tokens, state) = tokenize_text(grammar, lines, line, previous);
store.tokens[line] = tokens;
- store.brackets[line] = None;
- store.plain_brackets[line] = None;
+ store.brackets.lines[line] = None;
+ store.plain_brackets.lines[line] = None;
store.set_end_state(line, state);
}
}
@@ -775,13 +769,13 @@ mod tests {
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.len(), 2);
+ 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.len(), 3);
+ 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.len(), 0, "the comment opened above hides line 2's brackets");
+ assert_eq!(tokens.pairs(&languages, &lines, "typescript").pairs_in_lines(0..lines.len()).len(), 0, "the comment opened above hides line 2's brackets");
}
/// Typing latency on a 52k-line TypeScript file (textModel.ts repeated): the median per edit of one typed char
diff --git a/port/ledger.md b/port/ledger.md
index 393f4da69e1..69da7f5a6a4 100644
--- a/port/ledger.md
+++ b/port/ledger.md
@@ -285,8 +285,8 @@ One row per upstream unit, generated by `bun port/tools/gen-ledger.ts`; mileston
| platform/windows | src/vs/platform | M11 | verified | | windows_state.rs (windowsStateHandler.ts, windowsMainService.ts `doGetPathsFromLastSession`): `windowsState` in `User/globalStorage/storage.json` saved on quit (the last window closed, else the active one; all windows when two or more), restored on a start without paths and on every start with `preserve` (`window.restoreWindows` none, one, folders, all), each window in its display and bounds when that display is still there, fullscreen only with `window.restoreFullscreen`; empty windows reopen on their backup folder; a reload keeps the window's place; a new window takes the stored place of its workspace, folder or empty window, the first one the last active window's, else `window.newWindowDimensions` (default and offset cascade 30 points off the open windows, inherit, maximized, fullscreen). The default size stays 1024x768, the reference capture size of port/tools/ref-screenshot, where upstream takes 1200x800 or 1440x900. `cargo test -p app windows_state`; verified: ui-pair hot-exit.json `restored` vs the reference (port/results/windows.md, milestone 11 verification): the window restored on its folder after quit |
| platform/workspace | src/vs/platform | M12 | verified | | virtual workspaces (non-file folders): milestone 25; config/src/workspace.rs: folders, getFolder, toWorkspaceFolders, workspace label; cargo test -p config workspace (workspace.test.ts cases); api-workspace 4/4; verified: api-tests MOCHA_GREP="vscode API - (workspace|file system|env|types|tasks)" at 44a309311e1: every workspace, workspace-fs, workspace events, workspace-watcher and file system test passes, api-workspace 4/0/0 (port/results/api-tests.md "M12 verification"), api-workspace 4/4 |
| platform/workspaces | src/vs/platform | M12 | verified | | getWorkspaceIdentifier and getSingleFolderWorkspaceIdentifier (session.rs, workspaces.test.ts stable id case, cargo test -p exthost); recently opened list (recently_opened.rs, workspacesHistoryMainService: `history.recentlyOpenedPathsList` in shared storage, 500 per kind, cargo test -p app recently_opened); untitled workspaces under `<user data>/Workspaces/<id>/workspace.json` (config/src/workspace.rs isUntitledWorkspace, workbench/workspace_editing.rs createUntitledWorkspace, deleteUntitledWorkspace, Save Workspace As with rewritten relative paths): cargo test -p config workspace:: 5/5, cargo test -p app workspace_editing; ui-pair port/fixtures/ui-pair/m12/workspace-folders.json (Remove Folder from Workspace enters Untitled (Workspace)), verified at port-m12b-verify; getWorkspaceIdentifier and getSingleFolderWorkspaceIdentifier (session.rs, workspaces.test.ts stable id case, cargo test -p exthost); no untitled workspaces or recent list; getWorkspaceIdentifier and getSingleFolderWorkspaceIdentifier (session.rs, workspaces.test.ts stable id case, cargo test -p exthost); recently opened list (recently_opened.rs, workspacesHistoryMainService: `history.recentlyOpenedPathsList` in shared storage, 500 per kind, cargo test -p app recently_opened); no untitled workspaces; getWorkspaceIdentifier and getSingleFolderWorkspaceIdentifier (session.rs, workspaces.test.ts stable id case, cargo test -p exthost); no untitled workspaces or recent list |
-| editor/browser | src/vs/editor | M8 | ported | [3 S] word_wrap.rs:136: a view line starting inside an inlay hint in a smaller font or with the padding box draws the hint's rest at an even share of its drawn width, upstream splits the spans <br> [3 L] syntax.rs:318, :355: incremental bracket tree. Gate: cargo test --release -p app -- --ignored typing_latency_on_a_large_file (one typed char then the tokens of 60 visible lines and the bracket match, 52k-line TS file of textModel.ts repeated, median per edit under 16 ms). Before the token store (80b459587ac): 5.6 s at line 100, 2.8 s at line 25000, 0.5 s at line 49000. With the token store, each line's brackets kept and the folding update Delayer: 9.3 ms, 9.9 ms, 10.3 ms, of which pairing the 78k brackets again 6.5 ms <br> [scheduling L] minimap.rs:87; minimap_view.rs:432; unicode_highlight.rs:63; indentation.rs:43; comment.rs:45; smart_select.rs:292: sticky minimap sampling, worker section headers and unicode highlights, tokenizeIfCheap, the 30 ms smart select yield. Accepted as "Scheduling differences" only with a measured same result and typing on a 50k-line TS file under 16 ms per edit; otherwise class 3. Audit inputs at 5e5b1b0a915. | scrolling: wheel, scrollbars with drag, track press and fade, scroll shadow, reveal on cursor moves and from the API, per-editor scroll position (editor/view.rs, workbench/editor_view.rs): cargo test -p app editor::view::tests (8); folding (editor/folding.rs): cargo test -p app editor::folding (49); minimap with slider, decorations, section headers, settings and the scrollbar context menu (editor/minimap.rs, editor/section_headers.rs, workbench/minimap_view.rs): cargo test -p app minimap (11), section_headers (18), editor_menus (8); sticky scroll (editor/contrib/stickyScroll row); rounded selections (`editor.roundedSelection`): cargo test -p app selection_corners (1); `editor.renderWhitespace` (editor/whitespace.rs): cargo test -p app whitespace (39); control characters and bidi format characters as `[U+XXXX]` (workbench/control_characters.rs): cargo test -p app control_characters (4); glyph margin and line number presses (workbench/gutter_mouse.rs): cargo test -p app gutter_presses (1); word wrap with view lines, Toggle Word Wrap and the wrap indicator (editor/word_wrap.rs): cargo test -p app word_wrap (21), ui-pair /tmp/m8wrap wrap.ts; `editor.smoothScrolling` (editor/smooth_scroll.rs, workbench/smooth_scrolling.rs): cargo test -p app smooth_scroll (11, the scrollable.test.ts cases); diff editor widget (port/notes.md milestone 14): cargo test -p app diff_editor (22), diff_gutter (2); all run at the milestone 20 sweep; scrolling: wheel, scrollbars with drag, track press and fade, scroll shadow, reveal on cursor moves and from the API, per-editor scroll position (editor/view.rs, workbench/editor_view.rs): cargo test -p app editor::view::tests; folding (editor/folding.rs): cargo test -p app editor::folding; minimap with slider, decorations and section headers (editor/minimap.rs, editor/section_headers.rs, workbench/minimap_view.rs): cargo test -p app minimap, cargo test -p app section_headers; sticky scroll (editor/contrib/stickyScroll row); rounded selections (`editor.roundedSelection`, selections.ts): cargo test -p app selection_corners, ui-pair corners match; `editor.renderWhitespace` marks drawn as svg circles and arrows (editor/whitespace.rs, viewParts/whitespace): cargo test -p app whitespace, ui-pair notes.txt; control characters as Control Pictures (`editor.renderControlCharacters`, workbench/control_characters.rs): cargo test -p app control_characters; glyph margin and line number presses select lines, drags extend them, Alt adds a line cursor (mouseHandler.ts `startedOnLineNumbers`, workbench/gutter_mouse.rs): cargo test -p app gutter_presses; no smooth scrolling, no word wrap (`editor.wordWrap`, viewModelLines with line breaks), bidi format characters not drawn as `[U+XXXX]` (port/notes.md milestone 8); diff editor widget (side by side, inline, view zones, gutter toolbar, overview ruler, title actions; port/notes.md milestone 14): cargo test -p app diff_editor diff_gutter; Switch Side (`diffEditor.switchSide`, the selection mapped through the diff) and Focus Primary, Secondary and Other Side, in the diff and the multi diff editor: cargo test -p app switch_side; bracket pair guides (`editor.guides.bracketPairs`, `bracketPairsHorizontal`, `highlightActiveBracketPair`; guidesTextModelPart.ts) in every code editor, on a wrapped line only on the view lines `getViewLinesBracketGuides` keeps (viewModelLines.ts): cargo test -p app bracket_pair_guide; indent guides on a wrapped line repeated on its view lines only with a wrapping indent (`getViewLinesIndentGuides`, viewModelLines.ts), none past the wrapping column (`_maxIndentLeft`, indentGuides.ts): cargo test -p app wrapping_indent_repeats without_a_wrapping_indent; scrolling: wheel, scrollbars with drag, track press and fade, scroll shadow, reveal on cursor moves and from the API, per-editor scroll position (editor/view.rs, workbench/editor_view.rs): cargo test -p app editor::view::tests; folding (editor/folding.rs): cargo test -p app editor::folding; minimap with slider, decorations and section headers (editor/minimap.rs, editor/section_headers.rs, workbench/minimap_view.rs): cargo test -p app minimap, cargo test -p app section_headers; sticky scroll (editor/contrib/stickyScroll row); rounded selections (`editor.roundedSelection`, selections.ts): cargo test -p app selection_corners, ui-pair corners match; no `renderWhitespace` yet; no smooth scrolling (port/notes.md milestone 8); scrolling: wheel, scrollbars with drag, track press and fade, scroll shadow, reveal on cursor moves and from the API, per-editor scroll position (editor/view.rs, workbench/editor_view.rs): cargo test -p app editor::view::tests; folding (editor/folding.rs): cargo test -p app editor::folding; minimap with slider, decorations and section headers (editor/minimap.rs, editor/section_headers.rs, workbench/minimap_view.rs): cargo test -p app minimap, cargo test -p app section_headers; sticky scroll (editor/contrib/stickyScroll row); rounded selections (`editor.roundedSelection`, selections.ts): cargo test -p app selection_corners, ui-pair corners match; `editor.renderWhitespace` marks drawn as svg circles and arrows (editor/whitespace.rs, viewParts/whitespace): cargo test -p app whitespace, ui-pair notes.txt; control characters as Control Pictures (`editor.renderControlCharacters`, workbench/control_characters.rs): cargo test -p app control_characters; glyph margin and line number presses select lines, drags extend them, Alt adds a line cursor (mouseHandler.ts `startedOnLineNumbers`, workbench/gutter_mouse.rs): cargo test -p app gutter_presses; word wrap with view lines, Toggle Word Wrap and the wrap indicator (editor/word_wrap.rs: cargo test -p app word_wrap; ui-pair /tmp/m8wrap wrap.ts: breaks, End, Down and Alt+Z match the reference); bidi format characters as `[U+XXXX]` (cargo test -p app control_characters); minimap settings and the scrollbar context menu (cargo test -p app minimap editor_menus); `editor.smoothScrolling` over 125 ms for cursor, find and API reveals and mouse wheel notches (editor/smooth_scroll.rs, workbench/smooth_scrolling.rs: cargo test -p app smooth_scroll, the scrollable.test.ts cases); diff editor widget (side by side, inline, view zones, gutter toolbar, overview ruler, title actions; port/notes.md milestone 14): cargo test -p app diff_editor diff_gutter; each side its own editor (the original's cursor and active line number, inline only its line numbers wide), char changes filled past the line break (`shouldFillLineOnLineBreak`) but not in the inline deleted lines, the sides' overview ruler without the minimap background, a press with no move before it shows the scrollbars: cargo test -p app file_compare char_ranges a_click_without_a_move, ui-pair m12/compare.json; mouse selection: four clicks select all, a double click the word (`WordOperations.word`) or the inside of brackets and strings (`editor.doubleClickSelectsBlock`), double and triple click drags go on by words and lines, their Alt forms on the cursor added last, a drag past the text scrolls each frame (dragScrolling.ts) (editor/mouse_selection.rs, workbench/drag_scrolling.rs): cargo test -p app mouse_selection text_clicks_select a_selecting_drag_below (6), in the vertical scrollbar without the minimap, below the horizontal scrollbar's top and in a comment reply editor: cargo test -p app a_drag_into_the_vertical the_bottom_edge_hit a_drag_below_a_comment; the IME input handler sees the selection's lines, a caret inside marked text places the cursor and character bounds follow the text (nativeEditContext.ts): cargo test -p app text_input::; decoration type outlines outside the range and borders inside it, the CSS cascade of their shorthands and longhands, `before`/`after` content text as injected text (workbench/editor_view/text_decorations.rs): cargo test -p app outline_and_border_follow_the_css_cascade a_decoration_outline_is_drawn_outside_its_range decoration_types_set_and_remove_editor_decorations, ui-pair of a merge conflict file: the header's "(Incoming Change)" text matches the reference |
-| editor/common | src/vs/editor | M8 | ported | [3 L] syntax.rs:318, :355: incremental bracket tree. Gate: cargo test --release -p app -- --ignored typing_latency_on_a_large_file (one typed char then the tokens of 60 visible lines and the bracket match, 52k-line TS file of textModel.ts repeated, median per edit under 16 ms). Before the token store (80b459587ac): 5.6 s at line 100, 2.8 s at line 25000, 0.5 s at line 49000. With the token store, each line's brackets kept and the folding update Delayer: 9.3 ms, 9.9 ms, 10.3 ms, of which pairing the 78k brackets again 6.5 ms <br> [scheduling L] minimap.rs:87; minimap_view.rs:432; unicode_highlight.rs:63; indentation.rs:43; comment.rs:45; smart_select.rs:292: sticky minimap sampling, worker section headers and unicode highlights, tokenizeIfCheap, the 30 ms smart select yield. Accepted as "Scheduling differences" only with a measured same result and typing on a 50k-line TS file under 16 ms per edit; otherwise class 3. Audit inputs at 5e5b1b0a915. | the model and cursor layer under every editor (app/src/editor, decorations.rs, link_computer.rs, syntax.rs, the diff crate): cursors (CursorCollection normalize, per-cursor edits, loser edits, paste distribution, column selection), core moves and deletes over grapheme clusters, typing with auto-closing, word operations, the edit stack with its stops and the alternative version id dirty state, onEnter and indentation rules (`languages/autoIndent.ts`, `enterAction.ts`, EnterOperation, electric characters, TabOperation, ShiftCommand miss-aligned lines), indentation guessing, model decorations with injected text, bracket matching and bracket pair colorization, the lines in view past the tokenized ones tokenized from a guessed start state (`tokenizeHeuristically`: cargo test -p app lines_in_view_past_the_tokenized_ones), the link computer, view lines with word wrap: cargo test -p app editor:: decorations:: link_computer syntax:: (781 passed, 13 ignored: the upstream `test.skip` cases of indentation.test.ts); the diff algorithms of editor/common/diff: cargo test -p diff (15 passed). `getWordAtPosition` inside the token language with its `wordPattern`: cargo test -p app the_word_at_a_column (model.test.ts 'Get word at position', 'getWordAtPosition at embedded language boundaries', 'issue #61296'). Swapped by design: the piece tree text buffer is a vector of lines (no observable difference; large files go through workbench/large_file.rs). Gap (editor audit): pushEOL not on the undo stack (edit.rs). Full-width chars take two visible columns for tab stops and cursor moves and draw at the font's full-width advance: cargo test -p app full_width_chars_take moving_down_keeps. Language configuration regexes read a class hyphen next to `\w`, `\d` or `\s` as JavaScript does (css `[\w-?]`, folding.rs `marker_regex`): cargo test -p app a_hyphen_next_to_a_class_escape_is_literal. |
+| editor/browser | src/vs/editor | M8 | ported | [3 S] word_wrap.rs:136: a view line starting inside an inlay hint in a smaller font or with the padding box draws the hint's rest at an even share of its drawn width, upstream splits the spans <br> [scheduling L] minimap.rs:87; minimap_view.rs:432; unicode_highlight.rs:63; indentation.rs:43; comment.rs:45; smart_select.rs:292: sticky minimap sampling, worker section headers and unicode highlights, tokenizeIfCheap, the 30 ms smart select yield. Accepted as "Scheduling differences" only with a measured same result and typing on a 50k-line TS file under 16 ms per edit; otherwise class 3. Audit inputs at 5e5b1b0a915. | scrolling: wheel, scrollbars with drag, track press and fade, scroll shadow, reveal on cursor moves and from the API, per-editor scroll position (editor/view.rs, workbench/editor_view.rs): cargo test -p app editor::view::tests (8); folding (editor/folding.rs): cargo test -p app editor::folding (49); minimap with slider, decorations, section headers, settings and the scrollbar context menu (editor/minimap.rs, editor/section_headers.rs, workbench/minimap_view.rs): cargo test -p app minimap (11), section_headers (18), editor_menus (8); sticky scroll (editor/contrib/stickyScroll row); rounded selections (`editor.roundedSelection`): cargo test -p app selection_corners (1); `editor.renderWhitespace` (editor/whitespace.rs): cargo test -p app whitespace (39); control characters and bidi format characters as `[U+XXXX]` (workbench/control_characters.rs): cargo test -p app control_characters (4); glyph margin and line number presses (workbench/gutter_mouse.rs): cargo test -p app gutter_presses (1); word wrap with view lines, Toggle Word Wrap and the wrap indicator (editor/word_wrap.rs): cargo test -p app word_wrap (21), ui-pair /tmp/m8wrap wrap.ts; `editor.smoothScrolling` (editor/smooth_scroll.rs, workbench/smooth_scrolling.rs): cargo test -p app smooth_scroll (11, the scrollable.test.ts cases); diff editor widget (port/notes.md milestone 14): cargo test -p app diff_editor (22), diff_gutter (2); all run at the milestone 20 sweep; scrolling: wheel, scrollbars with drag, track press and fade, scroll shadow, reveal on cursor moves and from the API, per-editor scroll position (editor/view.rs, workbench/editor_view.rs): cargo test -p app editor::view::tests; folding (editor/folding.rs): cargo test -p app editor::folding; minimap with slider, decorations and section headers (editor/minimap.rs, editor/section_headers.rs, workbench/minimap_view.rs): cargo test -p app minimap, cargo test -p app section_headers; sticky scroll (editor/contrib/stickyScroll row); rounded selections (`editor.roundedSelection`, selections.ts): cargo test -p app selection_corners, ui-pair corners match; `editor.renderWhitespace` marks drawn as svg circles and arrows (editor/whitespace.rs, viewParts/whitespace): cargo test -p app whitespace, ui-pair notes.txt; control characters as Control Pictures (`editor.renderControlCharacters`, workbench/control_characters.rs): cargo test -p app control_characters; glyph margin and line number presses select lines, drags extend them, Alt adds a line cursor (mouseHandler.ts `startedOnLineNumbers`, workbench/gutter_mouse.rs): cargo test -p app gutter_presses; no smooth scrolling, no word wrap (`editor.wordWrap`, viewModelLines with line breaks), bidi format characters not drawn as `[U+XXXX]` (port/notes.md milestone 8); diff editor widget (side by side, inline, view zones, gutter toolbar, overview ruler, title actions; port/notes.md milestone 14): cargo test -p app diff_editor diff_gutter; Switch Side (`diffEditor.switchSide`, the selection mapped through the diff) and Focus Primary, Secondary and Other Side, in the diff and the multi diff editor: cargo test -p app switch_side; bracket pair guides (`editor.guides.bracketPairs`, `bracketPairsHorizontal`, `highlightActiveBracketPair`; guidesTextModelPart.ts) in every code editor, on a wrapped line only on the view lines `getViewLinesBracketGuides` keeps (viewModelLines.ts): cargo test -p app bracket_pair_guide; indent guides on a wrapped line repeated on its view lines only with a wrapping indent (`getViewLinesIndentGuides`, viewModelLines.ts), none past the wrapping column (`_maxIndentLeft`, indentGuides.ts): cargo test -p app wrapping_indent_repeats without_a_wrapping_indent; scrolling: wheel, scrollbars with drag, track press and fade, scroll shadow, reveal on cursor moves and from the API, per-editor scroll position (editor/view.rs, workbench/editor_view.rs): cargo test -p app editor::view::tests; folding (editor/folding.rs): cargo test -p app editor::folding; minimap with slider, decorations and section headers (editor/minimap.rs, editor/section_headers.rs, workbench/minimap_view.rs): cargo test -p app minimap, cargo test -p app section_headers; sticky scroll (editor/contrib/stickyScroll row); rounded selections (`editor.roundedSelection`, selections.ts): cargo test -p app selection_corners, ui-pair corners match; no `renderWhitespace` yet; no smooth scrolling (port/notes.md milestone 8); scrolling: wheel, scrollbars with drag, track press and fade, scroll shadow, reveal on cursor moves and from the API, per-editor scroll position (editor/view.rs, workbench/editor_view.rs): cargo test -p app editor::view::tests; folding (editor/folding.rs): cargo test -p app editor::folding; minimap with slider, decorations and section headers (editor/minimap.rs, editor/section_headers.rs, workbench/minimap_view.rs): cargo test -p app minimap, cargo test -p app section_headers; sticky scroll (editor/contrib/stickyScroll row); rounded selections (`editor.roundedSelection`, selections.ts): cargo test -p app selection_corners, ui-pair corners match; `editor.renderWhitespace` marks drawn as svg circles and arrows (editor/whitespace.rs, viewParts/whitespace): cargo test -p app whitespace, ui-pair notes.txt; control characters as Control Pictures (`editor.renderControlCharacters`, workbench/control_characters.rs): cargo test -p app control_characters; glyph margin and line number presses select lines, drags extend them, Alt adds a line cursor (mouseHandler.ts `startedOnLineNumbers`, workbench/gutter_mouse.rs): cargo test -p app gutter_presses; word wrap with view lines, Toggle Word Wrap and the wrap indicator (editor/word_wrap.rs: cargo test -p app word_wrap; ui-pair /tmp/m8wrap wrap.ts: breaks, End, Down and Alt+Z match the reference); bidi format characters as `[U+XXXX]` (cargo test -p app control_characters); minimap settings and the scrollbar context menu (cargo test -p app minimap editor_menus); `editor.smoothScrolling` over 125 ms for cursor, find and API reveals and mouse wheel notches (editor/smooth_scroll.rs, workbench/smooth_scrolling.rs: cargo test -p app smooth_scroll, the scrollable.test.ts cases); diff editor widget (side by side, inline, view zones, gutter toolbar, overview ruler, title actions; port/notes.md milestone 14): cargo test -p app diff_editor diff_gutter; each side its own editor (the original's cursor and active line number, inline only its line numbers wide), char changes filled past the line break (`shouldFillLineOnLineBreak`) but not in the inline deleted lines, the sides' overview ruler without the minimap background, a press with no move before it shows the scrollbars: cargo test -p app file_compare char_ranges a_click_without_a_move, ui-pair m12/compare.json; mouse selection: four clicks select all, a double click the word (`WordOperations.word`) or the inside of brackets and strings (`editor.doubleClickSelectsBlock`), double and triple click drags go on by words and lines, their Alt forms on the cursor added last, a drag past the text scrolls each frame (dragScrolling.ts) (editor/mouse_selection.rs, workbench/drag_scrolling.rs): cargo test -p app mouse_selection text_clicks_select a_selecting_drag_below (6), in the vertical scrollbar without the minimap, below the horizontal scrollbar's top and in a comment reply editor: cargo test -p app a_drag_into_the_vertical the_bottom_edge_hit a_drag_below_a_comment; the IME input handler sees the selection's lines, a caret inside marked text places the cursor and character bounds follow the text (nativeEditContext.ts): cargo test -p app text_input::; decoration type outlines outside the range and borders inside it, the CSS cascade of their shorthands and longhands, `before`/`after` content text as injected text (workbench/editor_view/text_decorations.rs): cargo test -p app outline_and_border_follow_the_css_cascade a_decoration_outline_is_drawn_outside_its_range decoration_types_set_and_remove_editor_decorations, ui-pair of a merge conflict file: the header's "(Incoming Change)" text matches the reference |
+| editor/common | src/vs/editor | M8 | ported | [scheduling L] minimap.rs:87; minimap_view.rs:432; unicode_highlight.rs:63; indentation.rs:43; comment.rs:45; smart_select.rs:292: sticky minimap sampling, worker section headers and unicode highlights, tokenizeIfCheap, the 30 ms smart select yield. Accepted as "Scheduling differences" only with a measured same result and typing on a 50k-line TS file under 16 ms per edit; otherwise class 3. Audit inputs at 5e5b1b0a915. | the model and cursor layer under every editor (app/src/editor, decorations.rs, link_computer.rs, syntax.rs, the diff crate): cursors (CursorCollection normalize, per-cursor edits, loser edits, paste distribution, column selection), core moves and deletes over grapheme clusters, typing with auto-closing, word operations, the edit stack with its stops and the alternative version id dirty state, onEnter and indentation rules (`languages/autoIndent.ts`, `enterAction.ts`, EnterOperation, electric characters, TabOperation, ShiftCommand miss-aligned lines), indentation guessing, model decorations with injected text, bracket matching and bracket pair colorization over the incremental bracket tree (bracketPairsTree/, brackets/tree.rs: cargo test -p app brackets; typing on the 52k-line TS file 1.40, 1.73, 2.29 ms median per edit: cargo test --release -p app -- --ignored typing_latency_on_a_large_file), the lines in view past the tokenized ones tokenized from a guessed start state (`tokenizeHeuristically`: cargo test -p app lines_in_view_past_the_tokenized_ones), the link computer, view lines with word wrap: cargo test -p app editor:: decorations:: link_computer syntax:: (781 passed, 13 ignored: the upstream `test.skip` cases of indentation.test.ts); the diff algorithms of editor/common/diff: cargo test -p diff (15 passed). `getWordAtPosition` inside the token language with its `wordPattern`: cargo test -p app the_word_at_a_column (model.test.ts 'Get word at position', 'getWordAtPosition at embedded language boundaries', 'issue #61296'). Swapped by design: the piece tree text buffer is a vector of lines (no observable difference; large files go through workbench/large_file.rs). Gap (editor audit): pushEOL not on the undo stack (edit.rs). Full-width chars take two visible columns for tab stops and cursor moves and draw at the font's full-width advance: cargo test -p app full_width_chars_take moving_down_keeps. Language configuration regexes read a class hyphen next to `\w`, `\d` or `\s` as JavaScript does (css `[\w-?]`, folding.rs `marker_regex`): cargo test -p app a_hyphen_next_to_a_class_escape_is_literal. |
| editor/standalone | src/vs/editor | | removed | | Artur: internal infrastructure or developer tool with no 1:1 counterpart in the native port |
| editor/test | src/vs/editor | M6 | n/a | | upstream test infrastructure; the port tests with cargo test and port/tools |
| editor/contrib/anchorSelect | src/vs/editor/contrib | M8 | verified | | `editor/anchor_select.rs`: the four commands with their keys and `selectionAnchorSet`, the anchor moved by edits as a `NeverGrowsWhenTypingAtEdges` marker, the bar under the word highlights: cargo test -p app anchor; ui-pair notes.txt through the Command Palette; no hover message until editor hovers |
diff --git a/port/notes.md b/port/notes.md
index ca73f193e2d..5fa8648b51a 100644
--- a/port/notes.md
+++ b/port/notes.md
@@ -137,7 +137,7 @@ Done when: the colorize-tests fixtures give the reference's scopes and colors; p
- shortcut: no tree-sitter; upstream uses it for TypeScript only behind `editor.experimental.preferTreeSitter.typescript`, off by default.
- Token store (`syntax.rs` `TokenStore`, `syntax/invalid_lines.rs`; textModelTokens.ts `TrackingTokenizationStateStore`, `RangePriorityQueueImpl`, `DefaultBackgroundTokenizer`): each line keeps its tokens and end state; an edit marks its lines untrusted and keeps the old end state of its last line, and tokenizing stops where a new end state equals the old one (`StateStack::equals`, vscode-textmate `StateStackImpl.equals`). A drawn line is tokenized on demand from the first untrusted line; the rest runs in 1 ms chunks after the frame (`workbench/editor_view.rs` `schedule_background_tokenization`), and the bracket pairs are paired again when it is done. Bracket pairing reads the tokens as they are, a line not tokenized yet holds no brackets, as bracketPairsTree.ts does while the background tokenizer runs; it first tokenizes up to 20 untrusted lines so the edited line counts.
- Each line keeps its brackets (`brackets.rs` `line_brackets`) until its text or tokens change, under the drawing theme and under the empty theme `pairs` reads; the theme changing drops them.
-- shortcut: every edit pairs the brackets of all lines again (6.5 ms for 78k brackets); upstream's BracketPairsTree reuses the unchanged nodes. Measured by `typing_latency_on_a_large_file`, see the editor/common ledger row.
+- Bracket tree (`brackets/`: length.rs, ids.rs, edits.rs, tree.rs; bracketPairsTree/ ast.ts, concat23Trees.ts, nodeReader.ts, tokenizer.ts, parser.ts, beforeEditPositionMapper.ts, combineTextEditInfos.ts, smallImmutableSet.ts): `BracketCache` keeps the tree and queues each edit as a line-granular `TextEditInfo`; a line whose tokens changed is a same-length edit (`handleDidChangeTokens`), and the next read parses again reusing the unchanged nodes. The tokenizer reads each line's cached brackets, not the text, so its text tokens end at a bracket, after about 30 lines or 1500 bytes. Not ported: `hasUnmatchedClosingBracketAfter` (no consumer: the port has no auto-closing on type yet), `nestingLevelOfEqualBracketType` (`independentColorPoolPerBracketType` unsupported), `getFirstBracketBefore` (no consumer). Typing on the 52k-line TS file: 1.40, 1.73, 2.29 ms median per edit, was 9.3, 9.9, 10.3 ms.
- shortcut: `tokenColors` given as a path to a .tmTheme file is not read; no built-in theme uses one.
- shortcut: the theme type reaches the extension host after the eager extensions activate; upstream sends it before `$startExtensionHost`.
- shortcut: no Go to Bracket, Select to Bracket or Force Retokenize commands until keybindings and the command palette land.