Skip to content

Visual Studio Code, rebuilt in Rust

Rust
23.5 KB
Raw Blame
//! 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, Selection};
use super::edit::{ContentChanged, CursorEdit, EditKind, EditReason, Replace, 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,
    /// `editor.autoClosingOvertype`: "always", "auto" or "never".
    pub overtype: &'a str,
    /// `editor.autoSurround`: "languageDefined", "quotes", "brackets" or "never".
    pub surround: &'a str,
    pub word_separators: &'a str,
}

impl Default for Options<'_> {
    fn default() -> Self {
        Options { brackets: AutoClose::LanguageDefined, quotes: AutoClose::LanguageDefined, comments: AutoClose::LanguageDefined, overtype: "auto", surround: "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, `autoCloseBefore`, and the `surroundingPairs`, else
/// the auto-closing pairs.
#[derive(Default)]
pub struct CharacterPairs {
    pub pairs: Vec<Pair>,
    auto_close_before: Option<String>,
    surrounding: Vec<(String, String)>,
}

impl CharacterPairs {
    pub fn new(language: &str, config: &Value, brackets: Option<&[(String, String)]>) -> Self {
        let pairs: Vec<Pair> = 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(),
        };
        let surrounding = match config["surroundingPairs"].as_array() {
            Some(surrounding) => surrounding.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 => pairs.iter().map(|pair| (pair.open.clone(), pair.close.clone())).collect(),
        };
        CharacterPairs { pairs, auto_close_before: config["autoCloseBefore"].as_str().map(str::to_string), surrounding }
    }

    /// `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 {
    /// `AutoClosingOvertypeOperation`: typing the close char that sits after every empty cursor types over it.
    pub(super) fn auto_closing_overtype(&mut self, ch: char, auto: AutoIndent) -> Option<Vec<ContentChanged>> {
        if !self.is_auto_closing_overtype(ch, auto) {
            return None;
        }
        let ranges = self.selections.iter().map(|selection| (selection.head, Position::new(selection.head.line, selection.head.column + 1))).collect();
        Some(self.type_into(&ch.to_string(), ranges, "type").into_iter().collect())
    }

    /// `isAutoClosingOvertype`.
    fn is_auto_closing_overtype(&self, ch: char, auto: AutoIndent) -> bool {
        let overtype = auto.closing.overtype;
        if overtype == "never" {
            return false;
        }
        let document = self.document();
        let Some(rules) = auto.languages.rules(&document.language_id) else { return false };
        let closes_single_char = |pair: &Pair| pair.open.chars().count() == 1 && pair.close.chars().eq([ch]);
        if !rules.character_pairs.pairs.iter().any(closes_single_char) {
            return false;
        }
        self.selections.iter().all(|selection| {
            let position = selection.head;
            let text: Vec<char> = document.lines[position.line].chars().collect();
            // `beforeCharacter` is read only from upstream's 1-based column 3 on.
            let after_backslash = position.column > 1 && text[position.column - 1] == '\\';
            selection.is_empty()
                && text.get(position.column) == Some(&ch)
                && !(after_backslash && is_quote(ch))
                && (overtype != "auto" || self.auto_closed.iter().any(|action| action.characters.iter().any(|&(start, _)| start == position)))
        })
    }

    /// `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
    }

    /// cursor.ts `executeEdits` from a snippet or a suggestion: when every edit's text ends in the close of a one-char
    /// pair after its open, those closes are remembered as auto-closed (`_findAutoClosingPairs`).
    pub fn execute_edits_tracking_pairs(&mut self, edits: Vec<(Position, Position, String, bool)>, end_selections: Option<Vec<Selection>>, reason: EditReason, pairs: &[(String, String)]) -> Option<ContentChanged> {
        let Some(indices) = find_auto_closing_pairs(&edits, pairs) else { return self.execute_edits(edits, end_selections, reason) };
        let mut by_position: Vec<_> = edits.iter().zip(indices).map(|((start, end, text, _), indices)| (*start, *end, text.chars().count(), indices)).collect();
        by_position.sort_by_key(|edit| edit.0);
        let change = self.execute_edits(edits, end_selections, reason)?;
        // Where each text landed: lines move up by the line breaks the earlier edits removed, columns move only after
        // an earlier edit that ended on the same line.
        let mut action = AutoClosedAction::default();
        let (mut removed_lines, mut previous): (usize, Option<(Position, usize)>) = (0, None);
        for (start, end, length, (open, close)) in by_position {
            let column = match previous {
                Some((previous_end, new_end_column)) if previous_end.line == start.line => new_end_column + start.column - previous_end.column,
                _ => start.column,
            };
            let line = start.line - removed_lines;
            action.characters.push((Position::new(line, column + close), Position::new(line, column + close + 1)));
            action.enclosing.push((Position::new(line, column + open), Position::new(line, column + close + 1)));
            removed_lines += end.line - start.line;
            previous = Some((end, column + length));
        }
        self.auto_closed.push(action);
        Some(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))
    }

    /// `SurroundSelectionOperation`: typing a surrounding pair's open wraps every selection in the pair, which stays
    /// selected, between undo stops.
    pub(super) fn surround_selection(&mut self, ch: char, auto: AutoIndent) -> Option<Vec<ContentChanged>> {
        let close = self.surrounding_close(ch, auto)?;
        let edits = self.each_cursor(|selection| {
            let (start, end) = (selection.start(), selection.end());
            let open = Replace { start, end: start, text: ch.to_string() };
            let close = Replace { start: end, end, text: close.clone() };
            let shift = usize::from(start.line == end.line);
            CursorEdit::new(vec![open, close], Selection { anchor: Position::new(start.line, start.column + 1), head: Position::new(end.line, end.column + shift) })
        });
        Some(self.apply_between_stops(edits, TYPED).into_iter().collect())
    }

    /// `_isSurroundSelectionType` with `shouldSurroundChar`: the close of the pair `ch` opens when every selection
    /// holds more than blanks and none is one quote typed over with a quote.
    fn surrounding_close(&self, ch: char, auto: AutoIndent) -> Option<String> {
        let surround = auto.closing.surround;
        let allowed = match is_quote(ch) {
            true => matches!(surround, "quotes" | "languageDefined"),
            false => matches!(surround, "brackets" | "languageDefined"),
        };
        if !allowed {
            return None;
        }
        let document = self.document();
        let surrounding = &auto.languages.rules(&document.language_id)?.character_pairs.surrounding;
        // Upstream keeps the pairs in a map by open, so the last one wins.
        let (_, close) = surrounding.iter().rev().find(|(open, _)| open.chars().eq([ch]))?;
        for selection in &self.selections {
            let (start, end) = (selection.start(), selection.end());
            if selection.is_empty() {
                return None;
            }
            let mut selected = String::new();
            for line in start.line..=end.line {
                let text = &document.lines[line];
                let from = if line == start.line { byte_offset(text, start.column) } else { 0 };
                let to = if line == end.line { byte_offset(text, end.column) } else { text.len() };
                selected.push_str(&text[from..to]);
            }
            if selected.chars().all(|c| c == ' ' || c == '\t') {
                return None;
            }
            let mut chars = selected.chars();
            if is_quote(ch) && start.line == end.line && chars.next().is_some_and(is_quote) && chars.next().is_none() {
                return None;
            }
        }
        Some(close.clone())
    }

    /// `getAutoClosedCharacters`: where each auto-closed char starts.
    pub(super) fn auto_closed_characters(&self) -> Vec<Position> {
        self.auto_closed.iter().flat_map(|action| action.characters.iter().map(|&(start, _)| start)).collect()
    }

    /// `_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))
}


/// `_findAutoClosingPairs`: per edit, the char indices of the open and the close of the one-char pair whose close is
/// the text's last closing char, or nothing when one edit has no such pair or a line break.
fn find_auto_closing_pairs(edits: &[(Position, Position, String, bool)], pairs: &[(String, String)]) -> Option<Vec<(usize, usize)>> {
    if edits.is_empty() {
        return None;
    }
    let mut indices = Vec::new();
    for (_, _, text, _) in edits {
        if text.is_empty() || text.contains('\n') {
            return None;
        }
        let chars: Vec<char> = text.chars().collect();
        let close_index = chars.iter().rposition(|c| ")]}>'\"`".contains(*c))?;
        let close = chars[close_index];
        let mut candidates = pairs.iter().filter(|(open, pair_close)| open.chars().count() == 1 && pair_close.chars().eq([close]));
        let (open, _) = candidates.next()?;
        if candidates.next().is_some() {
            return None;
        }
        let open = open.chars().next().expect("a one-char open");
        let open_index = chars[..close_index].iter().rposition(|&c| c == open)?;
        indices.push((open_index, close_index));
    }
    Some(indices)
}

#[cfg(test)]
mod tests;