Visual Studio Code, rebuilt in Rust
Rust
feat(editor): auto-close typed brackets and quotes
rokartur2737cfd7cb0a
diff --git a/native/crates/app/src/brackets.rs b/native/crates/app/src/brackets.rsindex 2aa04bf2624..13aa7079ed2 100644--- a/native/crates/app/src/brackets.rs+++ b/native/crates/app/src/brackets.rs@@ -262,6 +262,13 @@ impl DocumentBrackets {})}+ /// `hasUnmatchedClosingBracketAfter`: a closing bracket of the opening bracket `open` at or after the position+ /// (line, byte) closes none of the brackets open around it.+ pub fn has_unmatched_closing_after(&self, brackets: &LanguageBrackets, open: &str, line: usize, offset: usize) -> bool {+ let Some(token) = brackets.token(open).filter(|token| token.opening) else { return false };+ tree::has_unmatched_closing_after(&self.root, Length::new(line, offset), &token.ids)+ }+/// Every bracket of a pair, in document order.pub fn pair_brackets(&self) -> Vec<PairBracket> {let mut brackets = Vec::new();diff --git a/native/crates/app/src/brackets/tree.rs b/native/crates/app/src/brackets/tree.rsindex 6f45071ed31..7bad940b688 100644--- a/native/crates/app/src/brackets/tree.rs+++ b/native/crates/app/src/brackets/tree.rs@@ -98,6 +98,32 @@ fn pair(open: Arc<Node>, child: Option<Arc<Node>>, close: Option<Arc<Node>>) ->}/// `ListAstNode.create` and `create23`: children of one height.+/// bracketPairsTree.ts `hasUnmatchedClosingBracketAfter`: a closing bracket at or after `position` that closes one of+/// `ids` and none of the brackets open around it.+pub fn has_unmatched_closing_after(root: &Arc<Node>, position: Length, ids: &BracketIds) -> bool {+ if !root.missing().intersects(ids) {+ return false;+ }+ let mut to_visit = vec![(root, Length::ZERO)];+ while let Some((node, offset)) = to_visit.pop() {+ if let Node::Unexpected { .. } = **node {+ if offset >= position {+ return true;+ }+ continue;+ }+ let mut child_offset = offset;+ for child in node.children() {+ let child_end = child_offset + child.length();+ if child_end >= position && child.missing().intersects(ids) {+ to_visit.push((child, child_offset));+ }+ child_offset = child_end;+ }+ }+ false+}+pub fn list(children: Vec<Arc<Node>>) -> Arc<Node> {let mut length = Length::ZERO;let mut missing = BracketIds::EMPTY;diff --git a/native/crates/app/src/editor.rs b/native/crates/app/src/editor.rsindex 74d0fff6fa7..3f5a84981e4 100644--- a/native/crates/app/src/editor.rs+++ b/native/crates/app/src/editor.rs@@ -22,6 +22,7 @@ use crate::languages::Languages;use crate::syntax::Tokenization;mod anchor_select;+pub mod auto_closing;pub mod auto_indent;mod bracket_matching;mod caret_operations;@@ -790,6 +791,8 @@ pub struct OpenEditor {seen_version: u32,/// The snippet session of snippetController2.ts, its placeholders tracked through edits.pub snippet_session: Option<snippet_session::SnippetSession>,+ /// cursor.ts `_autoClosedActions`.+ auto_closed: Vec<auto_closing::AutoClosedAction>,pub word_wrap: word_wrap::WordWrap,/// The text this editor injects between the model's chars (inlay hints, color boxes), by position.pub injected_text: Vec<injected_text::InjectedText>,@@ -825,7 +828,7 @@ impl OpenEditor {let model = model.borrow();(model.version_id, word_wrap::WordWrap::new(&model.document.lines, model.document.too_large_for_tokenization))};- let mut editor = OpenEditor { seen_version, model, preview, sticky: false, model_id, selections: vec![Selection::default()], cursor_changed: false, last_added: 0, leftovers: Vec::new(), past_injections: None, column_select: None, selection_start: None, smart_select: None, cursor_states: Default::default(), highlights: Vec::new(), value_set_replacement: None, selection_anchor: None, folding: FoldingModel::default(), syntax_folding: false, folded_imports: false, folding_stale: false, sticky_model: Default::default(), folding_limit: folding::MAX_FOLDING_REGIONS_FOR_INDENT, folding_limited: None, sticky_outline: None, scroll: Scroll::default(), max_line_width: 0., view_zones: Vec::new(), snippet_session: None, word_wrap, text_decorations: Vec::new(), injected_text: Vec::new(), cursor_style_override: None, line_numbers_override: None, peek_preview: None };+ let mut editor = OpenEditor { seen_version, model, preview, sticky: false, model_id, selections: vec![Selection::default()], cursor_changed: false, last_added: 0, leftovers: Vec::new(), past_injections: None, column_select: None, selection_start: None, smart_select: None, cursor_states: Default::default(), highlights: Vec::new(), value_set_replacement: None, selection_anchor: None, folding: FoldingModel::default(), syntax_folding: false, folded_imports: false, folding_stale: false, sticky_model: Default::default(), folding_limit: folding::MAX_FOLDING_REGIONS_FOR_INDENT, folding_limited: None, sticky_outline: None, scroll: Scroll::default(), max_line_width: 0., view_zones: Vec::new(), snippet_session: None, auto_closed: Vec::new(), word_wrap, text_decorations: Vec::new(), injected_text: Vec::new(), cursor_style_override: None, line_numbers_override: None, peek_preview: None };editor.refresh_highlights();editor.refresh_folding_ranges();editordiff --git a/native/crates/app/src/editor/auto_closing.rs b/native/crates/app/src/editor/auto_closing.rsnew file mode 100644index 00000000000..fcd725d120f--- /dev/null+++ b/native/crates/app/src/editor/auto_closing.rs@@ -0,0 +1,334 @@+//! Auto-closing on type: cursorTypeEditOperations.ts `AutoClosingOpenCharTypeOperation` with its+//! `TypeWithAutoClosingCommand`, the pairs of a language configuration (characterPair.ts, languageConfiguration.ts+//! `StandardAutoClosingPairConditional`), and the auto-closed characters the cursors track (cursor.ts `AutoClosedAction`).++use serde_json::Value;+use textmate::StandardTokenType;++use super::OpenEditor;+use super::auto_indent::{AutoIndent, parse_regex};+use super::cursor::Position;+use super::edit::{ContentChanged, CursorEdit, EditKind, TYPED};+use super::word_operations::{CharClass, DEFAULT_WORD_SEPARATORS, WordClassifier};++/// characterPair.ts `DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED_QUOTES` and `..._BRACKETS`.+const AUTO_CLOSE_BEFORE_QUOTES: &str = ";:.,=}])> \n\t";+const AUTO_CLOSE_BEFORE_BRACKETS: &str = "'\"`;:.,=}])> \n\t";++/// `EditorAutoClosingStrategy`.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum AutoClose {+ Always,+ LanguageDefined,+ BeforeWhitespace,+ Never,+}++impl AutoClose {+ /// `editor.autoClosingBrackets`, `editor.autoClosingQuotes` and `editor.autoClosingComments`: "languageDefined"+ /// unless set to one of the other values.+ pub fn from_setting(value: Option<&Value>) -> Self {+ match value.and_then(Value::as_str) {+ Some("always") => AutoClose::Always,+ Some("beforeWhitespace") => AutoClose::BeforeWhitespace,+ Some("never") => AutoClose::Never,+ _ => AutoClose::LanguageDefined,+ }+ }++ /// `CursorConfiguration.shouldAutoCloseBefore`: whether a pair auto-closes before `next`.+ fn closes_before(self, language_defined: &str, next: char) -> bool {+ match self {+ AutoClose::Always => true,+ AutoClose::LanguageDefined => language_defined.contains(next),+ AutoClose::BeforeWhitespace => next == ' ' || next == '\t',+ AutoClose::Never => false,+ }+ }+}++/// The auto-closing options of `CursorConfiguration`.+#[derive(Clone, Copy)]+pub struct Options<'a> {+ pub brackets: AutoClose,+ pub quotes: AutoClose,+ pub comments: AutoClose,+ pub word_separators: &'a str,+}++impl Default for Options<'_> {+ fn default() -> Self {+ Options { brackets: AutoClose::LanguageDefined, quotes: AutoClose::LanguageDefined, comments: AutoClose::LanguageDefined, word_separators: DEFAULT_WORD_SEPARATORS }+ }+}++/// `StandardAutoClosingPairConditional`.+pub struct Pair {+ pub open: String,+ pub close: String,+ /// The token types of `notIn`, where the pair does not auto-close.+ not_in: Vec<StandardTokenType>,+ before_text: Option<onig::Regex>,+}++impl Pair {+ fn is_ok(&self, token_type: StandardTokenType) -> bool {+ !self.not_in.contains(&token_type)+ }++ /// `findNeutralCharacter`: the first of 0-9, a-z, A-Z in neither the open nor the close.+ fn neutral_character(&self) -> Option<char> {+ ('0'..='9').chain('a'..='z').chain('A'..='Z').find(|&c| !self.open.contains(c) && !self.close.contains(c))+ }+}++/// `CharacterPairSupport`: the `autoClosingPairs`, else the brackets, and `autoCloseBefore`.+#[derive(Default)]+pub struct CharacterPairs {+ pub pairs: Vec<Pair>,+ auto_close_before: Option<String>,+}++impl CharacterPairs {+ pub fn new(language: &str, config: &Value, brackets: Option<&[(String, String)]>) -> Self {+ let pairs = match config["autoClosingPairs"].as_array() {+ Some(pairs) => pairs.iter().enumerate().filter_map(|(i, pair)| auto_closing_pair(language, i, pair)).collect(),+ None => brackets.unwrap_or_default().iter().map(|(open, close)| Pair { open: open.clone(), close: close.clone(), not_in: Vec::new(), before_text: None }).collect(),+ };+ CharacterPairs { pairs, auto_close_before: config["autoCloseBefore"].as_str().map(str::to_string) }+ }++ /// `getAutoCloseBeforeSet`.+ fn auto_close_before(&self, quotes: bool) -> &str {+ match &self.auto_close_before {+ Some(chars) => chars,+ None if quotes => AUTO_CLOSE_BEFORE_QUOTES,+ None => AUTO_CLOSE_BEFORE_BRACKETS,+ }+ }+}++/// One entry of `autoClosingPairs`: `[open, close]` or `{ open, close, notIn, beforeText }`.+fn auto_closing_pair(language: &str, i: usize, pair: &Value) -> Option<Pair> {+ let open = pair[0].as_str().or(pair["open"].as_str())?.to_string();+ let close = pair[1].as_str().or(pair["close"].as_str())?.to_string();+ let not_in = match &pair["notIn"] {+ Value::String(scope) => vec![scope.as_str()],+ Value::Array(scopes) => scopes.iter().filter_map(Value::as_str).collect(),+ _ => Vec::new(),+ };+ let not_in = not_in+ .into_iter()+ .filter_map(|scope| match scope {+ "string" => Some(StandardTokenType::String),+ "comment" => Some(StandardTokenType::Comment),+ "regex" => Some(StandardTokenType::RegEx),+ _ => None,+ })+ .collect();+ let before_text = (!pair["beforeText"].is_null()).then(|| parse_regex(language, &format!("autoClosingPairs[{i}].beforeText"), &pair["beforeText"])).flatten();+ Some(Pair { open, close, not_in, before_text })+}++fn is_quote(ch: char) -> bool {+ matches!(ch, '\'' | '"' | '`')+}++fn byte_offset(line: &str, column: usize) -> usize {+ line.char_indices().nth(column).map_or(line.len(), |(offset, _)| offset)+}++/// cursor.ts `AutoClosedAction`: the close chars one auto-closing typed, and the ranges from each typed open char to+/// its close, moved by later edits as decorations that never grow.+#[derive(Clone, Debug, Default)]+pub struct AutoClosedAction {+ characters: Vec<(Position, Position)>,+ enclosing: Vec<(Position, Position)>,+}++impl AutoClosedAction {+ /// `isValid`: each cursor, in order, sits strictly inside one of the enclosing ranges, all still on one line.+ fn is_valid(&self, selections: &[(Position, Position)]) -> bool {+ if self.enclosing.iter().any(|(start, end)| start.line != end.line) {+ return false;+ }+ let mut enclosing = self.enclosing.clone();+ enclosing.sort();+ selections.iter().enumerate().all(|(i, &(start, end))| enclosing.get(i).is_some_and(|&(open, close)| open < start && end < close))+ }++ /// The ranges move with the edit of `start..end` into text ending at `new_end`, never growing at their edges.+ pub(super) fn track(&mut self, start: Position, end: Position, new_end: Position) {+ for range in self.characters.iter_mut().chain(&mut self.enclosing) {+ range.0 = super::folding::tracked(range.0, start, end, new_end, false);+ range.1 = super::folding::tracked(range.1, start, end, new_end, true);+ }+ }+}++impl OpenEditor {+ /// `AutoClosingOpenCharTypeOperation`: typing the last char of an auto-closing pair's open at every cursor also+ /// inserts the close after it.+ pub(super) fn auto_closing_open_type(&mut self, ch: char, auto: AutoIndent) -> Option<Vec<ContentChanged>> {+ let (open, close) = self.auto_closing_pair(ch, auto)?;+ let edits = self.each_cursor(|selection| CursorEdit::replace(selection.head, selection.head, ch.to_string(), Position::new(selection.head.line, selection.head.column + 1)));+ Some(self.type_and_auto_close(edits, &open, &close))+ }++ /// The typing `edits`, each ending at its cursor, and `close` after each cursor: in the same edit after an undo stop,+ /// or for an open longer than the typed char after the edits and an undo stop (`typeAndAutoCloseWithUndoStop`), so+ /// undo first removes only the close.+ pub(super) fn type_and_auto_close(&mut self, edits: Vec<CursorEdit>, open: &str, close: &str) -> Vec<ContentChanged> {+ self.push_undo_stop();+ let mut changes = Vec::new();+ let edits = if open.chars().count() > 1 {+ changes.extend(self.apply_cursor_edits(edits, TYPED));+ self.push_undo_stop();+ self.each_cursor(|selection| CursorEdit::replace(selection.head, selection.head, String::new(), selection.head))+ } else {+ edits+ };+ changes.extend(self.type_with_auto_closing(edits, close));+ self.text_model_mut().history.last_kind = EditKind::TypingOther;+ changes+ }++ /// `TypeWithAutoClosingCommand`: each edit with `close` inserted after its cursor, which stays before it, and the+ /// close chars remembered as auto-closed (`_pushAutoClosedAction`).+ fn type_with_auto_closing(&mut self, mut edits: Vec<CursorEdit>, close: &str) -> Option<ContentChanged> {+ for edit in &mut edits {+ edit.replaces[0].text.push_str(close);+ }+ let change = self.apply_cursor_edits(edits, TYPED);+ let close_len = close.chars().count();+ let mut action = AutoClosedAction::default();+ for selection in &self.selections {+ let caret = selection.head;+ let end = Position::new(caret.line, caret.column + close_len);+ action.characters.push((caret, end));+ action.enclosing.push((Position::new(caret.line, caret.column.saturating_sub(1)), end));+ }+ self.auto_closed.push(action);+ change+ }++ /// `getAutoClosingPair` for typing `ch` at every cursor, all empty: the pair whose open it completes, with the close+ /// to insert.+ pub(super) fn auto_closing_pair(&self, ch: char, auto: AutoIndent) -> Option<(String, String)> {+ if self.selections.iter().any(|selection| !selection.is_empty()) {+ return None;+ }+ let document = self.document();+ let lines = &document.lines;+ let character_pairs = &auto.languages.rules(&document.language_id)?.character_pairs;+ let pairs = &character_pairs.pairs;+ let positions: Vec<Position> = self.selections.iter().map(|selection| selection.head).collect();+ let pair = find_pair_open(pairs, lines, &positions, ch)?;+ let options = auto.closing;+ let block_comment_start = auto.languages.block_comment(&document.language_id).map(|(start, _)| start);+ let (strategy, quotes, check_balance) = if is_quote(ch) {+ (options.quotes, true, false)+ } else if block_comment_start.is_some_and(|start| pair.open.contains(start)) {+ (options.comments, false, false)+ } else {+ (options.brackets, false, true)+ };+ if strategy == AutoClose::Never {+ return None;+ }+ let contained_close = contained_pair(pairs, pair).map_or("", |contained| contained.close.as_str());+ let mut contained_present = true;+ let classifier = WordClassifier::new(options.word_separators, &[]);+ for &position in &positions {+ let text = &lines[position.line];+ let offset = byte_offset(text, position.column);+ let (before, after) = text.split_at(offset);+ if !after.starts_with(contained_close) {+ contained_present = false;+ }+ if let Some(next) = after.chars().next()+ && !is_before_closing_brace(pairs, after)+ && !strategy.closes_before(character_pairs.auto_close_before(quotes), next)+ {+ return None;+ }+ if check_balance && strategy != AutoClose::Always && document.tokens.has_unmatched_closing_bracket_after(auto.languages, lines, &document.language_id, &pair.open, position.line, offset) {+ return None;+ }+ // Do not auto-close ' or " after a word character.+ if pair.open.chars().count() == 1 && matches!(ch, '\'' | '"') && strategy != AutoClose::Always && before.chars().last().is_some_and(|c| classifier.get(c) == CharClass::Regular) {+ return None;+ }+ if !document.tokens.is_cheap_to_tokenize(lines, position.line) {+ return None;+ }+ // `shouldAutoClose`: the token of the char before the cursor.+ let before_char = byte_offset(text, position.column.saturating_sub(1));+ if !pair.is_ok(document.tokens.token_type_at(lines, position.line, before_char)) {+ return None;+ }+ // A neutral char typed instead tells whether `ch` would start a string or end one.+ if let Some(neutral) = pair.neutral_character()+ && !pair.is_ok(document.tokens.token_type_if_inserting(lines, position.line, offset, neutral))+ {+ return None;+ }+ }+ let close = match contained_present {+ true => pair.close[..pair.close.len() - contained_close.len()].to_string(),+ false => pair.close.clone(),+ };+ Some((pair.open.clone(), close))+ }++ /// `_validateAutoClosedActions`, after every cursor change.+ pub(super) fn validate_auto_closed(&mut self) {+ let mut selections: Vec<_> = self.selections.iter().map(|selection| (selection.start(), selection.end())).collect();+ selections.sort();+ self.auto_closed.retain(|action| action.is_valid(&selections));+ }+}++/// `_findAutoClosingPairOpen`: the longest pair whose open ends in `ch` and the text before every cursor completes.+fn find_pair_open<'p>(pairs: &'p [Pair], lines: &[String], positions: &[Position], ch: char) -> Option<&'p Pair> {+ let mut result: Option<&Pair> = None;+ for candidate in pairs.iter().filter(|pair| pair.open.ends_with(ch)) {+ let open_len = candidate.open.chars().count();+ if result.is_some_and(|result| open_len <= result.open.chars().count()) {+ continue;+ }+ let completes = positions.iter().all(|position| {+ let before: String = lines[position.line].chars().take(position.column).collect();+ let typed: String = before.chars().skip(position.column.saturating_sub(open_len - 1)).chain([ch]).collect();+ typed == candidate.open && candidate.before_text.as_ref().is_none_or(|regex| regex.find(&format!("{before}{ch}")).is_some())+ });+ if completes {+ result = Some(candidate);+ }+ }+ result+}++/// `_findContainedAutoClosingPair`: the longest other pair inside `pair`, as `(` and `)` are in `(*` and `*)`.+fn contained_pair<'p>(pairs: &'p [Pair], pair: &Pair) -> Option<&'p Pair> {+ if pair.open.chars().count() <= 1 {+ return None;+ }+ let last = pair.close.chars().last()?;+ let mut result: Option<&Pair> = None;+ for candidate in pairs.iter().filter(|candidate| candidate.close.ends_with(last)) {+ if candidate.open != pair.open && pair.open.contains(&candidate.open) && pair.close.ends_with(&candidate.close) && result.is_none_or(|result| candidate.open.len() > result.open.len()) {+ result = Some(candidate);+ }+ }+ result+}++/// `_isBeforeClosingBrace`: the text after the cursor starts with a close and no open.+fn is_before_closing_brace(pairs: &[Pair], after: &str) -> bool {+ let starts_with = |token: &str| !token.is_empty() && after.starts_with(token);+ !pairs.iter().any(|pair| starts_with(&pair.open)) && pairs.iter().any(|pair| starts_with(&pair.close))+}++#[cfg(test)]+mod tests;diff --git a/native/crates/app/src/editor/auto_closing/grammar.json b/native/crates/app/src/editor/auto_closing/grammar.jsonnew file mode 100644index 00000000000..e70e916059d--- /dev/null+++ b/native/crates/app/src/editor/auto_closing/grammar.json@@ -0,0 +1,22 @@+{+ "scopeName": "source.auto-closing-test",+ "patterns": [{ "include": "#code" }],+ "repository": {+ "code": {+ "patterns": [+ { "name": "comment.line", "match": "//.*$" },+ { "begin": "/\\*", "end": "\\*/", "beginCaptures": { "0": { "name": "comment.block" } }, "endCaptures": { "0": { "name": "comment.block" } }, "contentName": "string.comment-body" },+ { "name": "string.quoted.single", "begin": "'", "end": "'", "patterns": [{ "include": "#string-content" }] },+ { "name": "string.quoted.double", "begin": "\"", "end": "\"", "patterns": [{ "include": "#string-content" }] },+ { "name": "string.quoted.template", "begin": "`", "end": "`", "patterns": [{ "include": "#string-content" }] },+ { "begin": "\\{", "end": "\\}", "patterns": [{ "include": "#code" }] }+ ]+ },+ "string-content": {+ "patterns": [+ { "match": "\\\\." },+ { "name": "meta.embedded.interpolation", "begin": "\\$\\{", "end": "\\}", "patterns": [{ "include": "#code" }] }+ ]+ }+ }+}diff --git a/native/crates/app/src/editor/auto_closing/tests.rs b/native/crates/app/src/editor/auto_closing/tests.rsnew file mode 100644index 00000000000..8ebdcaa3192--- /dev/null+++ b/native/crates/app/src/editor/auto_closing/tests.rs@@ -0,0 +1,414 @@+//! The auto-closing cases of cursor.test.ts ('Editor Controller'). Positions are upstream's 1-based (line, column).++use serde_json::{Value, json};++use super::*;+use crate::editor::auto_indent::Strategy;+use crate::editor::cursor::Selection;+use crate::editor::edit::tests::editor;+use crate::languages::Languages;+use crate::syntax::Tokenization;++/// The suite's setup: the configuration of `autoClosingLanguageId`.+fn auto_closing_language() -> Value {+ json!({+ "comments": { "blockComment": ["/*", "*/"] },+ "autoClosingPairs": [+ { "open": "{", "close": "}" },+ { "open": "[", "close": "]" },+ { "open": "(", "close": ")" },+ { "open": "'", "close": "'", "notIn": ["string", "comment"] },+ { "open": "\"", "close": "\"", "notIn": ["string"] },+ { "open": "`", "close": "`", "notIn": ["string", "comment"] },+ { "open": "/**", "close": " */", "notIn": ["string"] },+ { "open": "begin", "close": "end", "notIn": ["string"] },+ ],+ })+}++/// `usingCursor`: a model in a language with the configuration `config`, `editor.autoIndent` full.+struct Cursor {+ editor: OpenEditor,+ languages: Languages,+ options: Options<'static>,+}++impl Cursor {+ fn new(config: Value, lines: &[&str]) -> Self {+ let mut languages = Languages::new(&[]);+ languages.configure("testLanguage", &config);+ let mut editor = editor(&lines.join("\n"), "\n");+ editor.document_mut().language_id = "testLanguage".into();+ Cursor { editor, languages, options: Options::default() }+ }++ fn brackets(mut self, brackets: AutoClose) -> Self {+ self.options.brackets = brackets;+ self+ }++ fn quotes(mut self, quotes: AutoClose) -> Self {+ self.options.quotes = quotes;+ self+ }++ fn comments(mut self, comments: AutoClose) -> Self {+ self.options.comments = comments;+ self+ }++ /// `setupAutoClosingLanguageTokenization`: strings, comments and `${}` in strings tokenized by grammar.json.+ fn tokenized(mut self) -> Self {+ let folder = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/editor/auto_closing");+ let package = json!({ "contributes": { "grammars": [{ "language": "testLanguage", "scopeName": "source.auto-closing-test", "path": "grammar.json" }] } });+ let registry = textmate::Registry::new([(folder.as_path(), &package)]);+ self.editor.document_mut().tokens = Tokenization::new(registry.grammar("testLanguage"));+ self+ }++ fn select(&mut self, carets: &[(usize, usize)]) {+ self.editor.set_selections(carets.iter().map(|&(line, column)| Selection::caret(Position::new(line - 1, column - 1))).collect());+ }++ /// `viewModel.type(text, 'keyboard')`.+ fn type_text(&mut self, text: &str) {+ let auto = AutoIndent { languages: &self.languages, strategy: Strategy::Full, closing: self.options };+ self.editor.type_keyboard(text, auto, false);+ }++ fn carets(&self) -> Vec<(usize, usize)> {+ self.editor.selections.iter().map(|selection| (selection.head.line + 1, selection.head.column + 1)).collect()+ }++ fn line(&self, line: usize) -> String {+ self.editor.document().lines[line - 1].clone()+ }++ fn value(&self) -> String {+ self.editor.document().lines.join("\n")+ }++ /// `assertType`: typing `ch` at (line, column) inserts `expected`, then undo.+ fn assert_type(&mut self, line: usize, column: usize, ch: &str, expected: &str, message: &str) {+ let content = self.line(line);+ let (before, after) = content.split_at(byte_offset(&content, column - 1));+ self.select(&[(line, column)]);+ self.type_text(ch);+ assert_eq!(self.line(line), format!("{before}{expected}{after}"), "{message} @ ({line}, {column})");+ self.editor.undo();+ }++ /// The loop over `extractAutoClosingSpecialColumns`: typing `ch` before each column of each line inserts `closed`+ /// where the annotation has a `|`, else only `ch`.+ fn assert_annotated(&mut self, annotated: &[&str], ch: &str, closed: &str) {+ for (index, annotation) in annotated.iter().enumerate() {+ let line = index + 1;+ let special = special_columns(self.line(line).chars().count() + 1, annotation);+ for (column, special) in special.into_iter().enumerate().skip(1) {+ match special {+ true => self.assert_type(line, column, ch, closed, "auto closes"),+ false => self.assert_type(line, column, ch, ch, "does not auto close"),+ }+ }+ }+ }+}++/// `extractAutoClosingSpecialColumns`: index `column` (1-based, up to `max_column`) is true where a `|` precedes it.+fn special_columns(max_column: usize, annotated: &str) -> Vec<bool> {+ let mut result = vec![false; max_column + 1];+ let mut column = 1;+ for ch in annotated.chars() {+ match ch {+ '|' => result[column] = true,+ _ => column += 1,+ }+ }+ result+}++const LINES: [&str; 8] = ["var a = [];", "var b = `asd`;", "var c = 'asd';", "var d = \"asd\";", "var e = /*3*/\t3;", "var f = /** 3 */3;", "var g = (3+5);", "var h = { a: 'value' };"];++#[test]+fn issue_61070_backtick_auto_closes_after_a_word_character() {+ let mut cursor = Cursor::new(auto_closing_language(), &["const markup = highlight"]);+ cursor.assert_type(1, 25, "`", "``", "auto closes `");+}++#[test]+fn issue_132912_quotes_do_not_auto_close_when_closing_a_string() {+ let mut cursor = Cursor::new(auto_closing_language(), &["const t2 = `something ${t1}"]).tokenized();+ cursor.assert_type(1, 28, "`", "`", "does not auto close `");+}++#[test]+fn open_parens_default() {+ let mut cursor = Cursor::new(auto_closing_language(), &LINES);+ let annotated = [+ "var| a| |=| [|]|;|",+ "var| b| |=| |`asd|`|;|",+ "var| c| |=| |'asd|'|;|",+ "var| d| |=| |\"asd|\"|;|",+ "var| e| |=| /*3*/|\t3|;|",+ "var| f| |=| /**| 3| */3|;|",+ "var| g| |=| (3+5|)|;|",+ "var| h| |=| {| a|:| |'value|'| |}|;|",+ ];+ cursor.assert_annotated(&annotated, "(", "()");+}++#[test]+fn open_parens_whitespace() {+ let mut cursor = Cursor::new(auto_closing_language(), &LINES).brackets(AutoClose::BeforeWhitespace);+ let annotated = [+ "var| a| =| [|];|",+ "var| b| =| `asd`;|",+ "var| c| =| 'asd';|",+ "var| d| =| \"asd\";|",+ "var| e| =| /*3*/|\t3;|",+ "var| f| =| /**| 3| */3;|",+ "var| g| =| (3+5|);|",+ "var| h| =| {| a:| 'value'| |};|",+ ];+ cursor.assert_annotated(&annotated, "(", "()");+}++#[test]+fn open_parens_disabled_or_enabled_with_open_quotes_enabled_or_disabled() {+ let mut cursor = Cursor::new(auto_closing_language(), &["var a = [];"]).brackets(AutoClose::BeforeWhitespace).quotes(AutoClose::Never);+ cursor.assert_annotated(&["var| a| =| [|];|"], "(", "()");+ cursor.assert_annotated(&["var a = [];"], "'", "''");++ let mut cursor = Cursor::new(auto_closing_language(), &["var b = [];"]).brackets(AutoClose::Never).quotes(AutoClose::BeforeWhitespace);+ cursor.assert_annotated(&["var b =| [|];|"], "'", "''");+ cursor.assert_annotated(&["var b = [];"], "(", "()");+}++#[test]+fn configurable_open_parens() {+ let mut config = auto_closing_language();+ config["autoCloseBefore"] = json!("abc");+ let mut cursor = Cursor::new(config, &LINES).brackets(AutoClose::LanguageDefined);+ let annotated = [+ "v|ar |a = [|];|",+ "v|ar |b = `|asd`;|",+ "v|ar |c = '|asd';|",+ "v|ar d = \"|asd\";|",+ "v|ar e = /*3*/\t3;|",+ "v|ar f = /** 3| */3;|",+ "v|ar g = (3+5|);|",+ "v|ar h = { |a: 'v|alue' |};|",+ ];+ cursor.assert_annotated(&annotated, "(", "()");+}++#[test]+fn auto_pairing_can_be_disabled() {+ let mut cursor = Cursor::new(auto_closing_language(), &LINES).brackets(AutoClose::Never).quotes(AutoClose::Never);+ cursor.assert_annotated(&LINES, "(", "()");+ cursor.assert_annotated(&LINES, "\"", "\"\"");+}++#[test]+fn quote() {+ let mut cursor = Cursor::new(auto_closing_language(), &LINES);+ let annotated = [+ "var a |=| [|]|;|",+ "var b |=| `asd`|;|",+ "var c |=| 'asd'|;|",+ "var d |=| \"asd\"|;|",+ "var e |=| /*3*/|\t3;|",+ "var f |=| /**| 3 */3;|",+ "var g |=| (3+5)|;|",+ "var h |=| {| a:| 'value'| |}|;|",+ ];+ cursor.assert_annotated(&annotated, "'", "''");+}++#[test]+fn multi_character_autoclose() {+ let mut cursor = Cursor::new(auto_closing_language(), &["begi"]);+ cursor.select(&[(1, 5)]);+ cursor.type_text("n");+ assert_eq!(cursor.line(1), "beginend");++ let mut cursor = Cursor::new(auto_closing_language(), &["/*"]);+ cursor.select(&[(1, 3)]);+ cursor.type_text("*");+ assert_eq!(cursor.line(1), "/** */");+}++#[test]+fn issue_338693_undo_after_multi_character_autoclose_first_removes_only_the_auto_closed_characters() {+ let mut cursor = Cursor::new(auto_closing_language(), &["begi begi"]);+ cursor.select(&[(1, 5), (1, 10)]);+ cursor.type_text("n");+ let mut states = vec![(cursor.line(1), cursor.carets())];+ cursor.editor.undo();+ states.push((cursor.line(1), cursor.carets()));+ cursor.editor.undo();+ states.push((cursor.line(1), cursor.carets()));+ let expected = [("beginend beginend", vec![(1, 6), (1, 15)]), ("begin begin", vec![(1, 6), (1, 12)]), ("begi begi", vec![(1, 5), (1, 10)])];+ assert_eq!(states, expected.map(|(line, carets)| (line.to_string(), carets)));+}++#[test]+fn issue_338693_undo_after_multi_character_autoclose_with_auto_indentation_first_removes_only_the_auto_closed_characters() {+ let config = json!({+ "autoClosingPairs": [{ "open": "begin", "close": "end" }],+ "indentationRules": { "increaseIndentPattern": r"^\s*procedure\b", "decreaseIndentPattern": r"^\s*begin\b" },+ });+ let mut cursor = Cursor::new(config, &["\tfoo", "\tbegi"]);+ cursor.select(&[(2, 6)]);+ cursor.type_text("n");+ let mut states = vec![(cursor.line(2), cursor.carets())];+ cursor.editor.undo();+ states.push((cursor.line(2), cursor.carets()));+ cursor.editor.undo();+ states.push((cursor.line(2), cursor.carets()));+ let expected = [("beginend", vec![(2, 6)]), ("begin", vec![(2, 6)]), ("\tbegi", vec![(2, 6)])];+ assert_eq!(states, expected.map(|(line, carets)| (line.to_string(), carets)));+}++#[test]+fn before_text() {+ let config = json!({ "autoClosingPairs": [{ "open": "begin", "close": "end", "beforeText": r"(?:^|\s)begin$" }] });+ let mut cursor = Cursor::new(config.clone(), &["begi", "begi"]);+ cursor.select(&[(1, 5), (2, 5)]);+ cursor.type_text("n");+ let mut results = vec![cursor.value()];+ for text in ["prefixbegi", "prefix begi"] {+ let mut cursor = Cursor::new(config.clone(), &[text]);+ cursor.select(&[(1, text.len() + 1)]);+ cursor.type_text("n");+ results.push(cursor.value());+ }+ assert_eq!(results, ["beginend\nbeginend", "prefixbegin", "prefix beginend"]);+}++#[test]+fn before_text_falls_back_to_a_shorter_pair() {+ let config = json!({ "autoClosingPairs": [{ "open": "begin", "close": "end", "beforeText": r"(?:^|\s)begin$" }, { "open": "n", "close": "]" }] });+ let mut cursor = Cursor::new(config, &["prefixbegi"]);+ cursor.select(&[(1, 11)]);+ cursor.type_text("n");+ assert_eq!(cursor.value(), "prefixbegin]");+}++#[test]+fn doc_comments_can_be_turned_off() {+ let mut cursor = Cursor::new(auto_closing_language(), &["/*"]).comments(AutoClose::Never);+ cursor.select(&[(1, 3)]);+ cursor.type_text("*");+ assert_eq!(cursor.line(1), "/**");+}++#[test]+fn issue_72177_multi_character_autoclose_with_conflicting_patterns() {+ let config = json!({ "autoClosingPairs": [{ "open": "(", "close": ")" }, { "open": "(*", "close": "*)" }, { "open": "<@", "close": "@>" }, { "open": "<@@", "close": "@@>" }] });+ let mut cursor = Cursor::new(config.clone(), &[""]);+ cursor.type_text("(");+ assert_eq!(cursor.line(1), "()");+ cursor.type_text("*");+ assert_eq!(cursor.line(1), "(**)", "doesn't add entire close when already closed substring is there");++ let mut cursor = Cursor::new(config.clone(), &["("]);+ cursor.select(&[(1, 2)]);+ cursor.type_text("*");+ assert_eq!(cursor.line(1), "(**)", "does add entire close if not already there");++ let mut cursor = Cursor::new(config, &[""]);+ cursor.type_text("<@");+ assert_eq!(cursor.line(1), "<@@>");+ cursor.type_text("@");+ assert_eq!(cursor.line(1), "<@@@@>", "autocloses when before multi-character closing brace");+ cursor.type_text("(");+ assert_eq!(cursor.line(1), "<@@()@@>", "autocloses when before multi-character closing brace");+}++#[test]+fn issue_55314_do_not_auto_close_when_ending_with_open() {+ let config = json!({ "autoClosingPairs": [+ { "open": "{", "close": "}" },+ { "open": "[", "close": "]" },+ { "open": "(", "close": ")" },+ { "open": "'", "close": "'", "notIn": ["string", "comment"] },+ { "open": "\"", "close": "\"", "notIn": ["string"] },+ { "open": "B\"", "close": "\"", "notIn": ["string", "comment"] },+ { "open": "`", "close": "`", "notIn": ["string", "comment"] },+ { "open": "/**", "close": " */", "notIn": ["string"] },+ ] });+ let mut cursor = Cursor::new(config, &["little goat", "little LAMB", "little sheep", "Big LAMB"]);+ for (line, column) in [(1, 4), (2, 4), (3, 4), (4, 2), (4, 3)] {+ cursor.assert_type(line, column, "\"", "\"", "does not double quote when ending with open");+ }+}++#[test]+fn issue_27937_adding_an_item_to_the_front_of_a_list() {+ let mut cursor = Cursor::new(auto_closing_language(), &["var arr = [\"b\", \"c\"];"]);+ cursor.assert_type(1, 12, "\"", "\"", "does not over type and will not auto close");+}++#[test]+fn issue_6841_auto_closing_brackets_balance_brackets() {+ let config = json!({+ "brackets": [["{", "}"], ["[", "]"], ["(", ")"]],+ "autoClosingPairs": [{ "open": "{", "close": "}" }, { "open": "[", "close": "]" }, { "open": "(", "close": ")" }],+ });+ let cases = [+ ("\n}", (1, 1), "{", "{\n}"),+ ("", (1, 1), "{", "{}"),+ ("{}", (1, 2), "{", "{{}}"),+ ("{\n", (2, 1), "{", "{\n{}"),+ ("\n]", (1, 1), "{", "{}\n]"),+ (")\n", (2, 1), "(", ")\n()"),+ ("function foo() {\n\n}", (2, 1), "{", "function foo() {\n{}\n}"),+ ("someFunction);", (1, 13), "(", "someFunction();"),+ ("someFunction;", (1, 13), "(", "someFunction();"),+ ("someFunctionsomeParam);", (1, 13), "(", "someFunction(someParam);"),+ ];+ for (text, caret, ch, expected) in cases {+ let mut cursor = Cursor::new(config.clone(), &[text]);+ cursor.select(&[caret]);+ cursor.type_text(ch);+ assert_eq!(cursor.value(), expected, "{text:?}");+ }++ let mut cursor = Cursor::new(config.clone(), &["", "}", ""]);+ cursor.select(&[(1, 1), (3, 1)]);+ cursor.type_text("{");+ assert_eq!(cursor.value(), "{\n}\n{");++ let mut cursor = Cursor::new(config, &["", ")"]).brackets(AutoClose::Always);+ cursor.type_text("(");+ assert_eq!(cursor.value(), "()\n)");++ let mut config = auto_closing_language();+ config["brackets"] = json!([["{", "}"]]);+ let mut cursor = Cursor::new(config.clone(), &["", "\"}\""]).tokenized();+ cursor.type_text("{");+ assert_eq!(cursor.value(), "{}\n\"}\"");++ let mut cursor = Cursor::new(config, &["", "\"}\"", "// }"]).tokenized();+ let lines = cursor.editor.document().lines.clone();+ cursor.editor.document().tokens.line_tokens(&lines, 2);+ cursor.type_text("{");+ assert_eq!(cursor.value(), "{}\n\"}\"\n// }");+}++#[test]+fn issue_25658_do_not_auto_close_quotes_after_word_characters() {+ let mut cursor = Cursor::new(auto_closing_language(), &[""]);+ let steps = [("teste1 = teste' ok", "teste1 = teste' ok"), ("teste2 = teste 'ok", "teste2 = teste 'ok'"), ("teste3 = teste\" ok", "teste3 = teste\" ok"), ("teste4 = teste \"ok", "teste4 = teste \"ok\""), ("teste '", "teste ''"), ("teste \"", "teste \"\""), ("teste'", "teste'"), ("teste\"", "teste\"")];+ for (line, (typed, expected)) in steps.into_iter().enumerate() {+ if line > 0 {+ cursor.select(&[(line, cursor.line(line).chars().count() + 1)]);+ cursor.type_text("\n");+ }+ for ch in typed.chars() {+ cursor.type_text(&ch.to_string());+ }+ assert_eq!(cursor.line(line + 1), expected);+ }+}diff --git a/native/crates/app/src/editor/auto_indent.rs b/native/crates/app/src/editor/auto_indent.rsindex d15f14e2ded..1c2b5056b0b 100644--- a/native/crates/app/src/editor/auto_indent.rs+++ b/native/crates/app/src/editor/auto_indent.rs@@ -8,6 +8,7 @@ use std::borrow::Cow;use serde_json::Value;use textmate::StandardTokenType;+use super::auto_closing::{CharacterPairs, Options};use super::cursor::{self, Position};use super::folding::marker_regex;use super::edit::{ContentChanged, EditReason, command, end_of};@@ -95,6 +96,7 @@ pub struct LanguageRules {auto_closing_open_ends: Vec<char>,/// `autoClosingPairs` (or the brackets) as (open, close).pub auto_closing_pairs: Vec<(String, String)>,+ pub character_pairs: CharacterPairs,/// `wordPattern`: `getWordAtPosition` falls back to the default word pattern without one.pub word_pattern: Option<std::sync::Arc<onig::Regex>>,}@@ -104,7 +106,7 @@ fn is_match(regex: &onig::Regex, text: &str) -> bool {}/// `_parseRegex`, with the warning upstream logs for an invalid pattern.-fn parse_regex(language: &str, path: &str, value: &Value) -> Option<onig::Regex> {+pub(super) fn parse_regex(language: &str, path: &str, value: &Value) -> Option<onig::Regex> {let Some((pattern, flags)) = marker_pattern(value) else {eprintln!("[{language}]: language configuration: expected `{path}` to be a string or an object.");return None;@@ -123,13 +125,11 @@ impl LanguageRules {(pairs, rules.unwrap_or_default())});let electric = brackets.as_ref().filter(|pairs| !pairs.is_empty()).map(|pairs| electric_brackets(pairs));- let auto_closing_pairs: Vec<(String, String)> = match config["autoClosingPairs"].as_array() {- Some(pairs) => pairs.iter().filter_map(|pair| Some((pair[0].as_str().or(pair["open"].as_str())?.to_string(), pair[1].as_str().or(pair["close"].as_str())?.to_string()))).collect(),- None => brackets.unwrap_or_default(),- };+ let character_pairs = CharacterPairs::new(language, config, brackets.as_deref());+ let auto_closing_pairs: Vec<(String, String)> = character_pairs.pairs.iter().map(|pair| (pair.open.clone(), pair.close.clone())).collect();let auto_closing_open_ends = auto_closing_pairs.iter().filter_map(|(open, _)| open.chars().last()).collect();let word_pattern = (!config["wordPattern"].is_null()).then(|| parse_regex(language, "wordPattern", &config["wordPattern"])).flatten().map(std::sync::Arc::new);- LanguageRules { on_enter, indent, electric, auto_closing_open_ends, auto_closing_pairs, word_pattern }+ LanguageRules { on_enter, indent, electric, auto_closing_open_ends, auto_closing_pairs, character_pairs, word_pattern }}/// `OnEnterSupport.onEnter`.@@ -729,11 +729,13 @@ fn should(regex: &Option<onig::Regex>, text: &str) -> bool {regex.as_ref().is_some_and(|regex| is_match(regex, text))}-/// What the cursor's type operations read from `CursorConfiguration`: the language configurations and `editor.autoIndent`.+/// What the cursor's type operations read from `CursorConfiguration`: the language configurations, `editor.autoIndent`+/// and the auto-closing options.#[derive(Clone, Copy)]pub struct AutoIndent<'a> {pub languages: &'a Languages,pub strategy: Strategy,+ pub closing: Options<'a>,}impl<'a> AutoIndent<'a> {diff --git a/native/crates/app/src/editor/auto_indent/tests.rs b/native/crates/app/src/editor/auto_indent/tests.rsindex 13176c991d0..7e287fb78d8 100644--- a/native/crates/app/src/editor/auto_indent/tests.rs+++ b/native/crates/app/src/editor/auto_indent/tests.rs@@ -66,12 +66,12 @@ impl Cursor {/// `viewModel.type(text, 'keyboard')`.fn type_text(&mut self, text: &str) {- self.editor.type_keyboard(text, AutoIndent { languages: &self.languages, strategy: self.strategy }, false);+ self.editor.type_keyboard(text, AutoIndent { languages: &self.languages, strategy: self.strategy, closing: Default::default() }, false);}/// `CoreEditingCommands.Tab`.fn tab(&mut self) {- self.editor.tab(AutoIndent { languages: &self.languages, strategy: self.strategy });+ self.editor.tab(AutoIndent { languages: &self.languages, strategy: self.strategy, closing: Default::default() });}/// `assertCursor`: the selection as (anchor line, anchor column, head line, head column).@@ -558,7 +558,7 @@ mod typescript {fn shift(lines: &[&str], unshift: bool, selection: ((usize, usize), (usize, usize)), expected: &[&str], expected_selection: (usize, usize, usize, usize)) {let mut cursor = cursor(lines, Strategy::Full).tabs();cursor.select(selection.0, selection.1);- let auto = AutoIndent { languages: &cursor.languages, strategy: cursor.strategy };+ let auto = AutoIndent { languages: &cursor.languages, strategy: cursor.strategy, closing: Default::default() };match unshift {true => cursor.editor.outdent(auto),false => cursor.editor.indent_lines(auto),diff --git a/native/crates/app/src/editor/auto_indent/tests/indentation.rs b/native/crates/app/src/editor/auto_indent/tests/indentation.rsindex 4b7b40ca48e..1a97a5e15f2 100644--- a/native/crates/app/src/editor/auto_indent/tests/indentation.rs+++ b/native/crates/app/src/editor/auto_indent/tests/indentation.rs@@ -166,7 +166,7 @@ impl Cursor {/// `viewModel.paste(text, true)`, then `AutoIndentOnPaste.trigger(range)`.fn paste(&mut self, text: &str, (start_line, start_column): (usize, usize), (end_line, end_column): (usize, usize)) {self.editor.paste(crate::editor::Pasted { text, paste_on_new_line: true, multicursor_text: None, is_block: false }, true, false);- let auto = AutoIndent { languages: &self.languages, strategy: self.strategy };+ let auto = AutoIndent { languages: &self.languages, strategy: self.strategy, closing: Default::default() };self.editor.auto_indent_on_paste(Position::new(start_line - 1, start_column - 1), Position::new(end_line - 1, end_column - 1), auto, true);}}diff --git a/native/crates/app/src/editor/edit.rs b/native/crates/app/src/editor/edit.rsindex 3655f496680..6c73bcc6b1d 100644--- a/native/crates/app/src/editor/edit.rs+++ b/native/crates/app/src/editor/edit.rs@@ -61,7 +61,7 @@ pub enum EditReason {/// How many replaces a model keeps for its other editors to follow (`sync_with_model`).const MAX_LOGGED_EDITS: usize = 1000;-const TYPED: EditReason = EditReason::Cursor { kind: "type", detailed_source: "keyboard" };+pub(super) const TYPED: EditReason = EditReason::Cursor { kind: "type", detailed_source: "keyboard" };pub(super) fn command(id: &'static str) -> EditReason {EditReason::Cursor { kind: "executeCommands", detailed_source: id }@@ -94,7 +94,7 @@ pub struct ContentChanged {/// The version ids dirty state is measured by (textModel.ts); the undo elements are the undo/redo service's.#[derive(Debug)]pub struct History {- last_kind: EditKind,+ pub(super) last_kind: EditKind,/// `getAlternativeVersionId`: undo returns to the id the text had, so undoing to the saved text is clean.pub(super) alternative_version_id: u32,saved_alternative_version_id: u32,@@ -147,7 +147,7 @@ impl CursorEdit {CursorEdit { replaces, after }}- fn replace(start: Position, end: Position, text: String, caret: Position) -> Self {+ pub(super) fn replace(start: Position, end: Position, text: String, caret: Position) -> Self {CursorEdit { replaces: vec![Replace { start, end, text }], after: Selection::caret(caret) }}}@@ -209,6 +209,7 @@ impl OpenEditor {}}self.leftovers = leftovers;+ self.validate_auto_closed();if self.selections != previous {self.cursor_changed = true;self.record_cursor_state(previous);@@ -472,36 +473,44 @@ impl OpenEditor {/// the indentation rules outdent reindents its line, and a closing bracket takes its opening line's indent./// Each char is its own model change, as upstream.pub fn type_keyboard(&mut self, text: &str, auto: AutoIndent, overtype: bool) -> Vec<ContentChanged> {- let mut changes = Vec::new();- for ch in normalize_line_breaks(text).chars() {- let ch = ch.to_string();- let change = match ch.as_str() {- "\n" => self.enter(auto),- _ => match self.auto_indent_type(&ch, auto).or_else(|| self.electric_type(&ch, auto)) {- Some(change) => change,- None if overtype => self.type_overtyping(&ch),- None => self.type_text(&ch),- },- };- changes.extend(change);+ normalize_line_breaks(text).chars().flat_map(|ch| self.type_with_interceptors(ch, auto, overtype)).collect()+ }++ /// `typeWithInterceptors` for one char.+ fn type_with_interceptors(&mut self, ch: char, auto: AutoIndent, overtype: bool) -> Vec<ContentChanged> {+ if ch == '\n' {+ return self.enter(auto).into_iter().collect();+ }+ if let Some(changes) = self.auto_indent_type(ch, auto).or_else(|| self.auto_closing_open_type(ch, auto)) {+ return changes;}- changes+ let text = ch.to_string();+ let change = match self.electric_type(&text, auto) {+ Some(change) => change,+ None if overtype => self.type_overtyping(&text),+ None => self.type_text(&text),+ };+ change.into_iter().collect()}- /// `AutoIndentOperation`: typing `ch` reindents every cursor's line, or `None` when one keeps its indentation.- fn auto_indent_type(&mut self, ch: &str, auto: AutoIndent) -> Option<Option<ContentChanged>> {+ /// `AutoIndentOperation`: typing `ch` reindents every cursor's line, and auto-closes as+ /// `TypeWithIndentationAndAutoClosingCommand`, or `None` when one keeps its indentation.+ fn auto_indent_type(&mut self, ch: char, auto: AutoIndent) -> Option<Vec<ContentChanged>> {let document = self.document();let model = auto.model(&document);let mut edits = Vec::new();for selection in &self.selections {- let (start, end, text, caret) = model.type_edit(selection.start(), selection.end(), ch)?;+ let (start, end, text, caret) = model.type_edit(selection.start(), selection.end(), &ch.to_string())?;edits.push(CursorEdit::replace(start, end, text, caret));}drop(document);+ if let Some((open, close)) = self.auto_closing_pair(ch, auto) {+ return Some(self.type_and_auto_close(edits, &open, &close));+ }self.push_undo_stop();let change = self.apply_cursor_edits(edits, TYPED);self.text_model_mut().history.last_kind = EditKind::TypingOther;- Some(change)+ Some(change.into_iter().collect())}/// `InterceptorElectricCharOperation`, for one cursor only: an undo stop after the reindented line.@@ -1129,6 +1138,9 @@ impl OpenEditor {for injection in &mut self.injected_text {injection.position = folding::tracked(injection.position, start, end, new_end, injection.at_range_start);}+ for action in &mut self.auto_closed {+ action.track(start, end, new_end);+ }}let lines = &model.document.lines;let clamp = |position: Position| {@@ -1148,6 +1160,7 @@ impl OpenEditor {self.seen_version = version;self.selections = selections;cursor::normalize(&mut self.selections, &mut self.last_added);+ self.validate_auto_closed();self.leftovers.clear();self.highlights.clear();if !logged {@@ -1163,6 +1176,7 @@ impl OpenEditor {self.cursor_changed = true;self.clear_cursor_states();cursor::normalize(&mut self.selections, &mut self.last_added);+ self.validate_auto_closed();self.leftovers.clear();self.highlights.clear();let mut model = self.text_model_mut();@@ -1206,6 +1220,9 @@ impl OpenEditor {self.track_markers(start, end, text);self.track_view_zones(start, end, text);self.track_injected_text(start, end, text);+ for action in &mut self.auto_closed {+ action.track(start, end, end_of(start, text));+ }if let Some(session) = self.snippet_session.as_mut() {session.track(start, end, text);}@@ -1459,7 +1476,7 @@ pub(super) mod tests {/// `TestLanguageConfigurationService` with no language registered.pub(in crate::editor) fn no_rules(strategy: Strategy) -> AutoIndent<'static> {- AutoIndent { languages: Box::leak(Box::new(Languages::new(&[]))), strategy }+ AutoIndent { languages: Box::leak(Box::new(Languages::new(&[]))), strategy, closing: Default::default() }}#[test]diff --git a/native/crates/app/src/editor/lines_operations/tests.rs b/native/crates/app/src/editor/lines_operations/tests.rsindex 593ca54691f..e1d3a55db75 100644--- a/native/crates/app/src/editor/lines_operations/tests.rs+++ b/native/crates/app/src/editor/lines_operations/tests.rs@@ -122,7 +122,7 @@ fn move_with_rules(config: serde_json::Value, down: bool, lines: &[&str], given:languages.configure("moveLinesMode", &config);let mut model = with_selections(lines, &[given]);model.document_mut().language_id = "moveLinesMode".into();- model.move_lines(down, AutoIndent { languages: &languages, strategy: Strategy::Full });+ model.move_lines(down, AutoIndent { languages: &languages, strategy: Strategy::Full, closing: Default::default() });assert_eq!(model.document().lines, expected);assert_eq!(selections(&model), [expected_selection]);}diff --git a/native/crates/app/src/editor/word_operations.rs b/native/crates/app/src/editor/word_operations.rsindex 4bb1417f5d8..d60c0451c6b 100644--- a/native/crates/app/src/editor/word_operations.rs+++ b/native/crates/app/src/editor/word_operations.rs@@ -11,7 +11,7 @@ use super::{Position, Selection};pub const DEFAULT_WORD_SEPARATORS: &str = super::WORD_SEPARATORS;#[derive(Clone, Copy, Debug, PartialEq)]-enum CharClass {+pub(super) enum CharClass {Regular,Whitespace,Separator,@@ -53,7 +53,7 @@ impl WordClassifier {WordClassifier { separators: separators.chars().collect(), segment: !segmenter_locales.is_empty() }}- fn get(&self, c: char) -> CharClass {+ pub(super) fn get(&self, c: char) -> CharClass {match c {' ' | '\t' => CharClass::Whitespace,c if self.separators.contains(&c) => CharClass::Separator,diff --git a/native/crates/app/src/syntax.rs b/native/crates/app/src/syntax.rsindex f7608296355..ea310260aaf 100644--- a/native/crates/app/src/syntax.rs+++ b/native/crates/app/src/syntax.rs@@ -270,6 +270,19 @@ impl Tokenization {tokens.iter().find(|token| token.end > offset).or(tokens.last()).map_or(textmate::StandardTokenType::Other, |token| token.token_type)}+ /// `getTokenTypeIfInsertingCharacter`: the standard type at byte `offset` of line `index` once `ch` is inserted there,+ /// the line tokenized again from its start state.+ pub fn token_type_if_inserting(&self, lines: &[String], index: usize, offset: usize, ch: char) -> textmate::StandardTokenType {+ let Some(grammar) = self.grammar.as_ref() else { return textmate::StandardTokenType::Other };+ self.tokenize_to(lines, index);+ let store = self.lines.borrow();+ let previous = index.checked_sub(1).and_then(|line| store.end_states[line].as_ref());+ let mut text = lines[index].clone();+ text.insert(offset, ch);+ let Ok((tokens, _)) = grammar.tokenize_line(&text, previous) else { return textmate::StandardTokenType::Other };+ tokens.iter().find(|token| token.end > offset).or(tokens.last()).map_or(textmate::StandardTokenType::Other, |token| token.token_type)+ }+/// inspectEditorTokens.ts `_getTokensAtPosition`: the token at byte `offset` of line `index` (the last one starting/// at or before it, else the first) from a fresh tokenization of the lines up to it, with no line length limit:/// its byte range, scopes and standard type; none without a grammar or tokens.@@ -321,6 +334,15 @@ impl Tokenization {self.document_brackets(&textmate::Theme::new(&[]), languages, lines, language, true)}+ /// bracketPairsImpl.ts `hasUnmatchedClosingBracketAfter` at (line, byte), false until every line has its tokens.+ pub fn has_unmatched_closing_bracket_after(&self, languages: &Languages, lines: &[String], language: &str, open: &str, line: usize, offset: usize) -> bool {+ if self.grammar.is_some() && self.synced(lines).invalid.min().is_some() {+ return false;+ }+ let Some(config) = languages.brackets.get(language) else { return false };+ self.pairs(languages, lines, language).has_unmatched_closing_after(config, open, line, offset)+ }+/// `bracket_guides` of lines `range` over the pairs the brackets were colored with, or `pairs` without a grammar.#[allow(clippy::too_many_arguments)]pub fn bracket_guides(&self, theme: &Theme, languages: &Languages, lines: &[String], language: &str, tab_size: usize, range: Range<usize>, cursor: Option<(usize, usize)>, options: &BracketGuideOptions) -> Vec<Vec<BracketGuide>> {diff --git a/native/crates/app/src/workbench/editor_commands.rs b/native/crates/app/src/workbench/editor_commands.rsindex de915c86e37..634f32db7e9 100644--- a/native/crates/app/src/workbench/editor_commands.rs+++ b/native/crates/app/src/workbench/editor_commands.rs@@ -11,6 +11,7 @@ use serde_json::{Value, json};use super::Workbench;use crate::commands::Outcome;+use crate::editor::auto_closing::{self, AutoClose};use crate::editor::auto_indent::{AutoIndent, Strategy};use crate::editor::word_operations::{self, AutoClosing, WordClassifier, WordDelete};use crate::editor::{CaseTransform, ContentChanged, LineCommentKind, OpenEditor, Pasted, Selection, clipboard, commands, smart_select};@@ -553,16 +554,22 @@ impl Workbench {self.editor_command_ran(change, selections_before, cx)}- /// Runs an editor command that indents by the language's rules, with `editor.autoIndent` of the- /// editor's language; each model change it makes reaches the host in turn.+ /// Runs an editor command that indents by the language's rules, with `editor.autoIndent` and the auto-closing+ /// settings of the editor's language; each model change it makes reaches the host in turn.pub(super) fn run_indenting(&mut self, command: impl FnOnce(&mut OpenEditor, AutoIndent) -> Vec<ContentChanged>, cx: &mut Context<Self>) -> Outcome {let Some(editor) = self.editors.active_mut() else { return Outcome::done() };let document = editor.document();let overrides = Overrides { resource: Some(&document.path), override_identifier: Some(&document.language_id) };- let strategy = Strategy::from_setting(self.settings.lock().unwrap().get_value(Some("editor.autoIndent"), &overrides).as_ref());+ let settings = self.settings.lock().unwrap();+ let setting = |key| settings.get_value(Some(key), &overrides);+ let strategy = Strategy::from_setting(setting("editor.autoIndent").as_ref());+ let word_separators = setting("editor.wordSeparators").and_then(|value| value.as_str().map(str::to_string)).unwrap_or(word_operations::DEFAULT_WORD_SEPARATORS.to_string());+ let (brackets, quotes, comments) = (setting("editor.autoClosingBrackets"), setting("editor.autoClosingQuotes"), setting("editor.autoClosingComments"));+ let closing = auto_closing::Options { brackets: AutoClose::from_setting(brackets.as_ref()), quotes: AutoClose::from_setting(quotes.as_ref()), comments: AutoClose::from_setting(comments.as_ref()), word_separators: &word_separators };+ drop(settings);let selections_before = editor.selections.clone();drop(document);- let changes = command(editor, AutoIndent { languages: &self.languages, strategy });+ let changes = command(editor, AutoIndent { languages: &self.languages, strategy, closing });self.editor_changes_ran(changes, selections_before, cx)}diff --git a/port/ledger.md b/port/ledger.mdindex d3b5b191407..6e4e0c96ef8 100644--- a/port/ledger.md+++ b/port/ledger.md@@ -286,7 +286,7 @@ One row per upstream unit, generated by `bun port/tools/gen-ledger.ts`; mileston| 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:157: an inlay hint with `editor.inlayHints.padding` broken by word wrap draws one padding box around both pieces, upstream's split spans each draw their own <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] edit.rs:474: typing does not auto-close brackets and quotes, overtype or delete the auto-closed ones, or surround a selection (`typeWithInterceptors` AutoClosingOvertype, AutoClosingOpenCharType, SurroundSelection in cursorTypeEditOperations.ts; cursor.test.ts autoClosing cases) <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, 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/common | src/vs/editor | M8 | ported | [3 L] edit.rs:480: typing does not overtype the auto-closed brackets and quotes or surround a selection, and Delete Left does not delete an auto-closed pair (`typeWithInterceptors` AutoClosingOvertype, SurroundSelection in cursorTypeEditOperations.ts; cursor.test.ts autoClosing overtype, surround and delete cases) <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, 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), auto-closing of typed brackets and quotes (`AutoClosingOpenCharTypeOperation`, `hasUnmatchedClosingBracketAfter`: cargo test -p app auto_closing), 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.mdindex 974a69d31c9..c3e7c27c5ab 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.-- 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.+- 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. `hasUnmatchedClosingBracketAfter` walks the unexpected closing brackets after the position for auto-closing on type. Not ported: `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.@@ -480,7 +480,8 @@ Done when (first item): api-tests `vscode API - editors` passes as in the refere- Line operations (`editor/lines_operations.rs`, editor/contrib/linesOperations): `CopyLinesCommand`, `MoveLinesCommand` and `SortLinesCommand` per selection through `execute_commands`, the other actions through `execute_edits` between undo stops, each with its upstream keys, the Selection menu group `2_line` and the palette; the case transforms register from `CaseTransform::ALL`. Computed end selections are validated as `Cursor.setStates` does (`valid_position` in `edit.rs`: a line past the document becomes the end of the last line, which Delete All Right relies on). Moved lines reindent by the language's rules (`MoveLinesCommand` with `editor.autoIndent`). Tests: `cargo test -p app editor::lines_operations line_operation_keys`, all of moveLinesCommand.test.ts. ui-pair: Alt+Down, Shift+Alt+Down, Ctrl+J give the reference's text and cursor.- Go to Line/Column and Go to Offset (`workbench/quick_access/goto_line.rs`, gotoLineQuickAccess.ts over editorNavigationQuickAccess.ts): `workbench.action.gotoLine` (Ctrl+G) and `workbench.action.gotoOffset` show quick access with `:` and `::`, both in the Command Palette. `parsePosition` with `line`, `line:col`, `line,col`, `line#col`, negative values from the end, visible columns over tabs, UTF-16 offsets, and the zero-based offset toggle (`index-zero` input button, `gotoLine.useZeroBasedOffset` in application storage). While the value changes the line is revealed in the center with `rangeHighlight` and a full-lane `editorOverviewRuler.rangeHighlightForeground` mark; Enter moves the cursor there (`code.jump`) and focuses the editor, accept in background keeps the picker, Escape or another prefix restores the view state. With `editor.lineNumbers` `relative` the editor numbers as `on` while the picker previews in it. Not ported: Alt or Cmd accept opening to the side (no editor groups), the aria status. Tests: `cargo test -p app go_to_line positions_parse`.- `editor.lineNumbers` `relative` and `interval` render as lineNumbers.ts `_getLineRenderLineNumber`: distances from the primary cursor with its own line number left-aligned (`.relative-current-line-number`), or every tenth line, the cursor's and the last (`cargo test -p app line_numbers`). `renderFinalNewline` is not applied to the number of an empty last line.-- Auto-indent (`editor/auto_indent.rs`, `languages/autoIndent.ts`, `enterAction.ts`, `cursorTypeEditOperations.ts`): `Languages::configure` parses `onEnterRules` and `indentationRules` beside the brackets; `Model` is upstream's virtual model over a document with one line replaced. Enter runs `EnterOperation._enter` (strategy none: plain newline; keep, or a line not cheap to tokenize: copy the indentation; else `getEnterAction` and `getIndentForEnter`), typing runs `AutoIndentOperation` then the electric closing bracket (`getIndentActionForType`, strategy full only), Tab on a blank line `TabOperation._goodIndentForLine`, Shift/Tab over lines `ShiftCommand` with its miss-aligned line heuristic (JSDoc ` * ` is not indentation). Insert Line Above/Below and Move Line Up/Down use the same rules. `editor.action.reindentlines` and `reindentselectedlines` (palette only, as upstream) run `getReindentEditOperations`. This replaces the milestone 5 shortcut "Enter copies the leading whitespace only". Not ported: auto-indent on paste (`editor.autoIndentOnPaste`, default off), auto-closing pairs. Tests: `cargo test -p app editor::auto_indent` (cursor.test.ts indent cases, indentation.test.ts Auto Indent On Type - TypeScript/JavaScript, shiftCommand.test.ts issues #348 and #1609). ui-pair on a `.ts` file: Enter after `{` and after `/** a` gives the reference's text (` x`, ` * b`).+- Auto-indent (`editor/auto_indent.rs`, `languages/autoIndent.ts`, `enterAction.ts`, `cursorTypeEditOperations.ts`): `Languages::configure` parses `onEnterRules` and `indentationRules` beside the brackets; `Model` is upstream's virtual model over a document with one line replaced. Enter runs `EnterOperation._enter` (strategy none: plain newline; keep, or a line not cheap to tokenize: copy the indentation; else `getEnterAction` and `getIndentForEnter`), typing runs `AutoIndentOperation` then the electric closing bracket (`getIndentActionForType`, strategy full only), Tab on a blank line `TabOperation._goodIndentForLine`, Shift/Tab over lines `ShiftCommand` with its miss-aligned line heuristic (JSDoc ` * ` is not indentation). Insert Line Above/Below and Move Line Up/Down use the same rules. `editor.action.reindentlines` and `reindentselectedlines` (palette only, as upstream) run `getReindentEditOperations`. This replaces the milestone 5 shortcut "Enter copies the leading whitespace only". Not ported: auto-indent on paste (`editor.autoIndentOnPaste`, default off). Tests: `cargo test -p app editor::auto_indent` (cursor.test.ts indent cases, indentation.test.ts Auto Indent On Type - TypeScript/JavaScript, shiftCommand.test.ts issues #348 and #1609). ui-pair on a `.ts` file: Enter after `{` and after `/** a` gives the reference's text (` x`, ` * b`).+- Auto-closing on type (`editor/auto_closing.rs`; cursorTypeEditOperations.ts `AutoClosingOpenCharTypeOperation`, `TypeWithAutoClosingCommand`, cursor.ts `AutoClosedAction`): `typeWithInterceptors` runs AutoIndent (which auto-closes too), then the open char, then the electric char. The pairs are the language's `autoClosingPairs` (else its brackets) with `notIn`, `beforeText` and `autoCloseBefore`; `editor.autoClosingBrackets`, `autoClosingQuotes`, `autoClosingComments` and `wordSeparators` come from the editor's language. A typed multi-char open (`begin`) gets an undo stop before its close, so undo first removes the close. Each editor keeps its auto-closed ranges as edit-tracked positions that never grow, dropped once a cursor leaves them. No composition (`chIsAlreadyTyped`) path and no reentrant content listeners, so cursor.test.ts's composition and reentrant-edit cases are not ported. Tests: `cargo test -p app auto_closing` (cursor.test.ts autoClosingPairs open, quote, multi-character, beforeText, issues #6841, #25658, #27937, #55314, #61070, #72177, #132912, #338693).- Smart select (`editor/smart_select.rs`, smartSelect.ts, wordSelections.ts, bracketSelections.ts): `OpenEditor::smart_select` keeps each cursor's ranges while the selections are the ones it set; the bracket ranges come from `Tokenization::pairs` (`DocumentBrackets.brackets`), words use the language's `wordPattern` (`LanguageRules::word_pattern`), else `word_at`. ui-pair on `foo(barBaz)` in a .ts file (Ctrl+Shift+Right 3 times, Ctrl+Shift+Left once): shrink matches the reference; the third expand gives `(barBaz)` where the reference, with the TypeScript extension's provider, gives `foo(barBaz)`. After the shrink the port draws the word highlight over the selected `barBaz`, the reference shows the plain selection color. In plain text both draw the highlight over the selected word (ui-pair on notes.txt), so the .ts difference is the TypeScript extension's document highlight provider; the port has only the textual one.- Word highlights follow `wordHighlighter.ts` `_run`: the word at the selection start, none when the selection reaches past it (`refresh_highlights`). The highlight paints above the selection as `DecorationsOverlay` sits above `SelectionsOverlay` (view.ts). Test: `cargo test -p app the_cursor_highlights_its_word`.- Word parts (`wordPartOperations.ts`, `cursorWordOperations.ts` `_moveWordPartLeft/Right`, `deleteWordPartLeft/Right`): the nearest of the word start, word end and camelCase/snake_case/kebab-case boundary; deletes take upstream's range comparators. Keys Ctrl+Alt+Left/Right (Shift selects), Ctrl+Alt+Backspace/Delete. Test: `cargo test -p app word_part` with the cases of `wordPartOperations.test.ts`.