Visual Studio Code, rebuilt in Rust
Rust
//! 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::editor::word_operations::{AutoClosing, DELETE_COMMANDS, NO_AUTO_CLOSING};
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
}
fn overtype(mut self, overtype: &'static str) -> Self {
self.options.overtype = overtype;
self
}
fn surround(mut self, surround: &'static str) -> Self {
self.options.surround = surround;
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());
}
/// Selections from (line, column) to (line, column).
fn select_ranges(&mut self, ranges: &[((usize, usize), (usize, usize))]) {
let position = |(line, column): (usize, usize)| Position::new(line - 1, column - 1);
self.editor.set_selections(ranges.iter().map(|&(anchor, head)| Selection { anchor: position(anchor), head: position(head) }).collect());
}
fn selections(&self) -> Vec<((usize, usize), (usize, usize))> {
let position = |position: Position| (position.line + 1, position.column + 1);
self.editor.selections.iter().map(|selection| (position(selection.anchor), position(selection.head))).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);
}
/// `CoreEditingCommands.DeleteLeft`, or with `word` `DeleteWordLeft`, with the language's pairs.
fn delete_left(&mut self, word: bool) {
let pairs = self.languages.rules("testLanguage").map(|rules| rules.auto_closing_pairs.clone()).unwrap_or_default();
let auto_closing = AutoClosing { pairs: &pairs, ..NO_AUTO_CLOSING };
if !word {
self.editor.delete_left(&auto_closing);
return;
}
let (id, word_delete) = DELETE_COMMANDS.into_iter().find(|(id, _)| *id == "deleteWordLeft").unwrap();
self.editor.delete_word(&WordClassifier::new(DEFAULT_WORD_SEPARATORS, &[]), &auto_closing, word_delete, id);
}
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);
}
}
#[test]
fn issue_37315_overtypes_only_those_characters_that_it_inserted() {
let mut cursor = Cursor::new(auto_closing_language(), &["", "y=();"]);
cursor.type_text("x=(");
assert_eq!(cursor.line(1), "x=()");
cursor.type_text("asd");
assert_eq!(cursor.line(1), "x=(asd)");
cursor.type_text(")");
assert_eq!(cursor.line(1), "x=(asd)", "overtype");
cursor.select(&[(2, 4)]);
cursor.type_text(")");
assert_eq!(cursor.line(2), "y=());", "do not overtype");
}
#[test]
fn issue_37315_stops_overtyping_once_cursor_leaves_area() {
let mut cursor = Cursor::new(auto_closing_language(), &["", "y=();"]);
cursor.type_text("x=(");
assert_eq!(cursor.line(1), "x=()");
cursor.select(&[(1, 5)]);
cursor.type_text(")");
assert_eq!(cursor.line(1), "x=())");
}
#[test]
fn issue_37315_it_overtypes_only_once() {
let mut cursor = Cursor::new(auto_closing_language(), &["", "y=();"]);
cursor.type_text("x=(");
assert_eq!(cursor.line(1), "x=()");
cursor.type_text(")");
assert_eq!(cursor.line(1), "x=()");
cursor.select(&[(1, 4)]);
cursor.type_text(")");
assert_eq!(cursor.line(1), "x=())");
}
#[test]
fn issue_37315_it_can_remember_multiple_auto_closed_instances() {
let mut cursor = Cursor::new(auto_closing_language(), &["", "y=();"]);
cursor.type_text("x=(");
assert_eq!(cursor.line(1), "x=()");
cursor.type_text("(");
assert_eq!(cursor.line(1), "x=(())");
cursor.type_text(")");
assert_eq!(cursor.line(1), "x=(())");
cursor.type_text(")");
assert_eq!(cursor.line(1), "x=(())");
}
#[test]
fn issue_78833_add_config_to_use_old_brackets_quotes_overtyping() {
let mut cursor = Cursor::new(auto_closing_language(), &["", "y=();"]).overtype("always");
cursor.type_text("x=(");
assert_eq!(cursor.line(1), "x=()");
cursor.type_text(")");
assert_eq!(cursor.line(1), "x=()");
cursor.select(&[(1, 4)]);
cursor.type_text(")");
assert_eq!(cursor.line(1), "x=()");
cursor.select(&[(2, 4)]);
cursor.type_text(")");
assert_eq!(cursor.line(2), "y=();");
}
#[test]
fn issue_53357_over_typing_ignores_characters_after_backslash() {
let mut cursor = Cursor::new(auto_closing_language(), &["console.log();"]);
cursor.select(&[(1, 13)]);
cursor.type_text("'");
assert_eq!(cursor.value(), "console.log('');");
cursor.type_text("it");
assert_eq!(cursor.value(), "console.log('it');");
cursor.type_text("\\");
assert_eq!(cursor.value(), "console.log('it\\');");
cursor.type_text("'");
assert_eq!(cursor.value(), "console.log('it\\'');");
}
#[test]
fn issue_84998_overtyping_brackets_does_not_work_after_backslash() {
let mut cursor = Cursor::new(auto_closing_language(), &[""]);
cursor.select(&[(1, 1)]);
cursor.type_text("\\");
assert_eq!(cursor.value(), "\\");
cursor.type_text("(");
assert_eq!(cursor.value(), "\\()");
cursor.type_text("abc");
assert_eq!(cursor.value(), "\\(abc)");
cursor.type_text("\\");
assert_eq!(cursor.value(), "\\(abc\\)");
cursor.type_text(")");
assert_eq!(cursor.value(), "\\(abc\\)");
}
#[test]
fn auto_wrapping_is_configurable() {
let mut cursor = Cursor::new(auto_closing_language(), &["var a = asd"]);
cursor.select_ranges(&[((1, 1), (1, 4)), ((1, 9), (1, 12))]);
cursor.type_text("`");
assert_eq!(cursor.value(), "`var` a = `asd`");
cursor.type_text("(");
assert_eq!(cursor.value(), "`(var)` a = `(asd)`");
let mut cursor = Cursor::new(auto_closing_language(), &["var a = asd"]).surround("never");
cursor.select_ranges(&[((1, 1), (1, 4))]);
cursor.type_text("`");
assert_eq!(cursor.value(), "` a = asd");
let mut cursor = Cursor::new(auto_closing_language(), &["var a = asd"]).surround("quotes");
cursor.select_ranges(&[((1, 1), (1, 4))]);
cursor.type_text("`");
assert_eq!(cursor.value(), "`var` a = asd");
cursor.type_text("(");
assert_eq!(cursor.value(), "`(` a = asd");
let mut cursor = Cursor::new(auto_closing_language(), &["var a = asd"]).surround("brackets");
cursor.select_ranges(&[((1, 1), (1, 4))]);
cursor.type_text("(");
assert_eq!(cursor.value(), "(var) a = asd");
cursor.type_text("`");
assert_eq!(cursor.value(), "(`) a = asd");
}
#[test]
fn bug_11476_double_bracket_surrounding_and_undo_is_broken() {
let mut cursor = Cursor::new(json!({ "autoClosingPairs": [{ "open": "(", "close": ")" }] }), &["hello"]);
cursor.select_ranges(&[((1, 3), (1, 5))]);
cursor.type_text("(");
assert_eq!(cursor.selections(), [((1, 4), (1, 6))]);
cursor.type_text("(");
assert_eq!(cursor.selections(), [((1, 5), (1, 7))]);
}
#[test]
fn issue_206774_surround_selection_with_empty_close_does_not_throw() {
let mut cursor = Cursor::new(json!({ "surroundingPairs": [{ "open": "<", "close": "" }] }), &["hello world"]);
cursor.select_ranges(&[((1, 1), (1, 6))]);
cursor.type_text("<");
assert_eq!(cursor.value(), "<hello world");
}
#[test]
fn issue_47733_undo_mangles_unicode_characters() {
let mut cursor = Cursor::new(json!({ "surroundingPairs": [{ "open": "%", "close": "%" }] }), &["'👁'"]);
cursor.select_ranges(&[((1, 1), (1, 2))]);
cursor.type_text("%");
assert_eq!(cursor.value(), "%'%👁'");
cursor.editor.undo();
assert_eq!(cursor.value(), "'👁'");
}
#[test]
fn issue_41825_special_handling_of_quotes_in_surrounding_pairs() {
let mut cursor = Cursor::new(json!({ "surroundingPairs": [{ "open": "\"", "close": "\"" }, { "open": "'", "close": "'" }] }), &["var x = 'hi';"]);
cursor.select_ranges(&[((1, 9), (1, 10)), ((1, 12), (1, 13))]);
cursor.type_text("\"");
assert_eq!(cursor.value(), "var x = \"hi\";");
cursor.select_ranges(&[((1, 9), (1, 10)), ((1, 12), (1, 13))]);
cursor.type_text("'");
assert_eq!(cursor.value(), "var x = 'hi';");
}
#[test]
fn issue_118270_auto_closing_deletes_only_those_characters_that_it_inserted() {
let mut cursor = Cursor::new(auto_closing_language(), &["", "y=();"]);
cursor.type_text("x=(");
assert_eq!(cursor.line(1), "x=()");
cursor.type_text("asd");
assert_eq!(cursor.line(1), "x=(asd)");
for _ in 0..3 {
cursor.delete_left(false);
}
assert_eq!(cursor.line(1), "x=()");
cursor.delete_left(false);
assert_eq!(cursor.line(1), "x=", "delete closing char");
cursor.select(&[(2, 4)]);
cursor.delete_left(false);
assert_eq!(cursor.line(2), "y=);", "do not delete closing char");
}
#[test]
fn delete_word_left_deletes_an_auto_closed_pair() {
let mut cursor = Cursor::new(auto_closing_language(), &["", "y=();"]);
cursor.type_text("x=(");
cursor.delete_left(true);
assert_eq!(cursor.line(1), "x=");
cursor.select(&[(2, 4)]);
cursor.delete_left(true);
assert_eq!(cursor.line(2), "y);", "deletes the word, not the pair it did not insert");
}
#[test]
fn all_cursors_should_do_the_same_thing_when_deleting_left() {
let mut cursor = Cursor::new(auto_closing_language(), &["var a = ()"]);
cursor.select(&[(1, 4), (1, 10)]);
cursor.delete_left(false);
assert_eq!(cursor.value(), "va a = )");
}
#[test]
fn issue_78527_does_not_close_quote_on_odd_count() {
let mut cursor = Cursor::new(auto_closing_language(), &["std::cout << '\"' << entryMap"]);
cursor.select(&[(1, 29)]);
let steps = [("[", "std::cout << '\"' << entryMap[]"), ("\"", "std::cout << '\"' << entryMap[\"\"]"), ("a", "std::cout << '\"' << entryMap[\"a\"]"), ("\"", "std::cout << '\"' << entryMap[\"a\"]"), ("]", "std::cout << '\"' << entryMap[\"a\"]")];
for (ch, expected) in steps {
cursor.type_text(ch);
assert_eq!(cursor.line(1), expected, "{ch}");
}
}
fn auto_closing_pairs(cursor: &Cursor) -> Vec<(String, String)> {
cursor.languages.rules("testLanguage").expect("configured").auto_closing_pairs.clone()
}
#[test]
fn issue_78975_parentheses_swallowing_does_not_work_when_parentheses_are_inserted_by_autocomplete() {
let mut cursor = Cursor::new(auto_closing_language(), &["<div id"]);
cursor.select(&[(1, 8)]);
let pairs = auto_closing_pairs(&cursor);
let edits = vec![(Position::new(0, 5), Position::new(0, 7), "id=\"\"".to_string(), false)];
cursor.editor.execute_edits_tracking_pairs(edits, Some(vec![Selection::caret(Position::new(0, 9))]), EditReason::Unknown("snippet"), &pairs);
assert_eq!(cursor.line(1), "<div id=\"\"");
cursor.type_text("a");
assert_eq!(cursor.line(1), "<div id=\"a\"");
cursor.type_text("\"");
assert_eq!(cursor.line(1), "<div id=\"a\"");
}
#[test]
fn issue_315131_parentheses_inserted_by_a_suggestion_are_tracked_as_auto_closed() {
let mut cursor = Cursor::new(auto_closing_language(), &["flo"]);
cursor.select(&[(1, 4)]);
let pairs = auto_closing_pairs(&cursor);
let edits = vec![(Position::new(0, 0), Position::new(0, 3), "floor()".to_string(), false)];
cursor.editor.execute_edits_tracking_pairs(edits, Some(vec![Selection::caret(Position::new(0, 6))]), EditReason::Unknown("suggest"), &pairs);
cursor.delete_left(false);
assert_eq!(cursor.line(1), "floor");
}
#[test]
fn pairs_from_several_edits_on_one_line_are_tracked_where_they_land() {
let mut cursor = Cursor::new(auto_closing_language(), &["a b"]);
let pairs = auto_closing_pairs(&cursor);
let edits = vec![(Position::new(0, 0), Position::new(0, 1), "f()".to_string(), false), (Position::new(0, 2), Position::new(0, 3), "g()".to_string(), false)];
cursor.editor.execute_edits_tracking_pairs(edits, Some(vec![Selection::caret(Position::new(0, 2)), Selection::caret(Position::new(0, 6))]), EditReason::Unknown("snippet"), &pairs);
cursor.type_text(")");
assert_eq!(cursor.line(1), "f() g()");
}