Skip to content

Visual Studio Code, rebuilt in Rust

Rust
34.7 KB
Raw Blame
//! The picks of the Command Palette (`AbstractCommandsQuickAccessProvider._getPicks` of
//! platform/quickinput/browser/commandsQuickAccess.ts): commands whose label matches the filter by words, by
//! accent-insensitive substring or by exact id, then "similar commands" by TF-IDF; recently used first.

use std::cmp::Ordering;
use std::sync::LazyLock;

use exthost::scan::ScannedExtension;
use serde_json::Value;

use crate::commands::Commands;
use crate::contextkey::{Context, Expr};
use crate::filters::{Matches, matches_base_contiguous_sub_string, matches_words, try_normalize_to_base};
use crate::keybindings::ExtensionSource;
use crate::notifications::Severity;
use crate::tf_idf::{Document, TfIdfCalculator, normalize_scores};

const TFIDF_THRESHOLD: f64 = 0.5;
const TFIDF_MAX_RESULTS: usize = 5;
/// `CommandsHistory.DEFAULT_COMMANDS_HISTORY_LENGTH`.
pub const DEFAULT_HISTORY_LENGTH: usize = 50;

/// An enabled command of `MenuId.CommandPalette`. The alias (`title.original`) equals the label in English,
/// the only language here, so it is left out.
#[derive(Clone, Debug, PartialEq)]
pub struct CommandPick {
    pub id: String,
    /// "Category: Title", or the title alone.
    pub label: String,
    pub category: Option<String>,
    /// `metadata.description`, which the TF-IDF match reads with the label.
    pub description: Option<String>,
}

#[derive(Debug, PartialEq)]
pub enum PaletteEntry {
    Separator(&'static str),
    Pick(Pick),
}

#[derive(Debug, PartialEq)]
pub struct Pick {
    pub id: String,
    pub label: String,
    /// The command id, when another pick has the same label.
    pub description: Option<String>,
    pub label_highlights: Matches,
    pub recently_used: bool,
    /// commandsQuickAccess.ts `toCommandPick`: `commandDescription.value` as the row's hover.
    // shortcut: a localized description's tooltip also shows its English original, split MenuItem.description when a language pack ships one.
    pub tooltip: Option<String>,
}

/// `CommandsHistory`: an LRU of command ids, each with the counter value of its last run.
pub struct CommandsHistory {
    /// Least recently used first.
    entries: Vec<(String, u64)>,
    counter: u64,
    limit: usize,
}

impl CommandsHistory {
    pub fn new(limit: usize) -> CommandsHistory {
        CommandsHistory { entries: Vec::new(), counter: 1, limit }
    }

    pub fn push(&mut self, id: &str) {
        self.entries.retain(|(entry, _)| entry != id);
        self.entries.push((id.to_owned(), self.counter));
        self.counter += 1;
        if self.entries.len() > self.limit {
            self.entries.drain(..self.entries.len() - self.limit);
        }
    }

    pub fn peek(&self, id: &str) -> Option<u64> {
        self.entries.iter().find(|(entry, _)| entry == id).map(|(_, counter)| *counter)
    }

    pub fn remove(&mut self, id: &str) {
        self.entries.retain(|(entry, _)| entry != id);
    }

    /// `CommandsHistory.clearHistory`.
    pub fn clear(&mut self) {
        *self = CommandsHistory::new(self.limit);
    }

    /// The LRU's `limit` setter: the oldest entries past the new limit go.
    pub fn set_limit(&mut self, limit: usize) {
        self.limit = limit;
        if self.entries.len() > limit {
            self.entries.drain(..self.entries.len() - limit);
        }
    }

    /// `CommandsHistory.load`: the `commandPalette.mru.cache` and `commandPalette.mru.counter` storage values.
    /// A cache written before `usesLRU` lists its entries in any order, so they are sorted by counter.
    pub fn load(cache: Option<&str>, counter: Option<&str>, limit: usize) -> CommandsHistory {
        let mut history = CommandsHistory::new(limit);
        let serialized = cache.and_then(|raw| match serde_json::from_str::<Value>(raw) {
            Ok(value) => Some(value),
            Err(error) => {
                eprintln!("[CommandsHistory] invalid data: {error}");
                None
            }
        });
        if let Some(serialized) = serialized {
            let mut entries: Vec<(String, u64)> = serialized["entries"]
                .as_array()
                .into_iter()
                .flatten()
                .filter_map(|entry| Some((entry["key"].as_str()?.to_owned(), entry["value"].as_u64()?)))
                .collect();
            if serialized["usesLRU"] != true {
                entries.sort_by_key(|(_, counter)| *counter);
            }
            for (id, counter) in entries {
                history.entries.retain(|(entry, _)| *entry != id);
                history.entries.push((id, counter));
            }
            history.set_limit(limit);
        }
        if let Some(counter) = counter.and_then(|raw| raw.parse().ok()) {
            history.counter = counter;
        }
        history
    }

    /// `CommandsHistory.saveState`: the cache and the counter as `load` reads them.
    pub fn serialize(&self) -> (String, String) {
        let entries: Vec<Value> = self.entries.iter().map(|(key, value)| serde_json::json!({ "key": key, "value": value })).collect();
        (serde_json::json!({ "usesLRU": true, "entries": entries }).to_string(), self.counter.to_string())
    }
}

struct Candidate<'a> {
    command: &'a CommandPick,
    label_highlights: Matches,
    tf_idf_score: Option<f64>,
}

pub fn command_picks(commands: &[CommandPick], filter: &str, history: &CommandsHistory) -> Vec<PaletteEntry> {
    let mut tf_idf_scores = None;
    let mut candidates = Vec::new();
    for command in commands {
        if let Some(label_highlights) = word_filter(filter, &command.label) {
            candidates.push(Candidate { command, label_highlights, tf_idf_score: None });
        } else if filter == command.id {
            candidates.push(Candidate { command, label_highlights: Vec::new(), tf_idf_score: None });
        } else if filter.encode_utf16().count() >= 3 {
            let scores = tf_idf_scores.get_or_insert_with(|| tf_idf(commands, filter));
            if let Some(score) = scores.iter().find(|score| score.key == command.id) {
                candidates.push(Candidate { command, label_highlights: Vec::new(), tf_idf_score: Some(score.score) });
            }
        }
    }
    candidates.sort_by(|a, b| compare(a, b, history));

    let mut entries = Vec::new();
    let mut add_other_separator = false;
    let mut add_suggested_separator = true;
    for (index, candidate) in candidates.iter().enumerate() {
        let recently_used = history.peek(&candidate.command.id).is_some();
        if index == 0 && recently_used {
            entries.push(PaletteEntry::Separator("recently used"));
            add_other_separator = true;
        }
        if add_suggested_separator && candidate.tf_idf_score.is_some() {
            entries.push(PaletteEntry::Separator("similar commands"));
            add_suggested_separator = false;
        }
        if add_other_separator && candidate.tf_idf_score.is_none() && !recently_used {
            entries.push(PaletteEntry::Separator("other commands"));
            add_other_separator = false;
        }
        let label = &candidate.command.label;
        let duplicate = candidates.iter().filter(|other| other.command.label == *label).count() > 1;
        entries.push(PaletteEntry::Pick(Pick {
            id: candidate.command.id.clone(),
            label: label.clone(),
            description: duplicate.then(|| candidate.command.id.clone()),
            label_highlights: candidate.label_highlights.clone(),
            recently_used,
            tooltip: candidate.command.description.clone(),
        }));
    }
    entries
}

/// An item of `MenuId.CommandPalette`: shown while `when` holds, enabled while `precondition` holds.
#[derive(Clone, Debug)]
pub struct MenuItem {
    pub id: String,
    pub title: String,
    pub category: Option<String>,
    /// `metadata.description`: the localized value, then the English one when it differs.
    pub description: Option<String>,
    pub when: Option<Expr>,
    pub precondition: Option<Expr>,
    /// The extension that contributed the command (`ICommandAction.source`).
    pub source: Option<ExtensionSource>,
}

/// The reference's command titles and `MenuId.CommandPalette` items without the extensions' ones, dumped from
/// 1.147.0 by port/tools/ref-commands. `labels` is what the Keyboard Shortcuts editor shows for each command id.
/// The dump's `productService.nameShort` (the update commands' category) and `applicationName` (the Shell Command
/// titles) become the port's.
pub(crate) static REFERENCE: LazyLock<Value> = LazyLock::new(|| {
    let application_name = format!("'{}'", crate::product::get("applicationName").as_str().expect("product.json has applicationName"));
    let reference = include_str!("command_palette/reference-commands.json").replace("Code - OSS Dev", crate::product::name_short()).replace("'code-oss'", &application_name);
    serde_json::from_str(&reference).expect("valid JSON")
});

impl MenuItem {
    /// "Category: Title"; upstream tests the category for truthiness, so emmet's `"category": ""` shows the title alone.
    pub fn label(&self) -> String {
        match &self.category {
            Some(category) if !category.is_empty() => format!("{category}: {}", self.title),
            _ => self.title.clone(),
        }
    }
}

/// The reference's label of a workbench or editor command: `MenuRegistry.getCommand`'s title, else the command
/// palette item's, else the editor action's (keybindingsEditor.ts `getActionsLabels`).
pub fn reference_label(id: &str) -> Option<&'static str> {
    REFERENCE["labels"][id].as_str()
}

/// Whether the reference registers `id` with `metadata.args` (`ICommandMetadata`).
pub fn has_args_metadata(id: &str) -> bool {
    REFERENCE["commandsWithArgs"].as_array().expect("an array").iter().any(|with_args| with_args == id)
}

/// `MenuRegistry.getMenuItems(MenuId.CommandPalette)`: the workbench's items, the extensions'
/// `contributes.menus.commandPalette` entries, then every other contributed command (`_appendImplicitItems`).
/// The workbench's items are the reference's; `enabled_commands` leaves out those the port does not register.
pub fn menu(extensions: &[ScannedExtension]) -> Vec<MenuItem> {
    let text = |value: &Value| value.as_str().map(str::to_string);
    let mut items: Vec<MenuItem> = REFERENCE["commandPalette"]
        .as_array()
        .expect("an array")
        .iter()
        .map(|item| MenuItem {
            id: text(&item["id"]).expect("an id"),
            title: text(&item["title"]).map(|title| crate::nls::localize_key(item["titleKey"].as_str(), &title).into_owned()).unwrap_or_default(),
            category: text(&item["category"]).map(|category| crate::nls::localize_key(item["categoryKey"].as_str(), &category).into_owned()),
            description: text(&item["description"]).map(|original| match crate::nls::localize_key(item["descriptionKey"].as_str(), &original) {
                value if value == original => original,
                value => format!("{value} ({original})"),
            }),
            when: item["when"].as_str().and_then(Expr::deserialize),
            precondition: item["precondition"].as_str().and_then(Expr::deserialize),
            source: None,
        })
        .collect();
    // update.contribution.ts `ShowReleaseNotesAction` (f1), registered only with product.json `releaseNotesUrl`, which the reference has not.
    if crate::product::get("releaseNotesUrl").is_string() {
        let category = Some(crate::product::name_short().to_owned());
        items.push(MenuItem { id: "update.showCurrentReleaseNotes".into(), title: "Show Release Notes".into(), category, description: None, when: None, precondition: None, source: None });
    }
    let mut commands: Vec<MenuItem> = Vec::new();
    for extension in extensions {
        for command in contributed_commands(extension) {
            // menusExtensionPoint.ts `handleCommand`: an id `MenuRegistry.getCommand` already knows.
            let owner = commands.iter().rev().find(|known| known.id == command.id).and_then(|known| known.source.as_ref()).and_then(|source| extensions.iter().find(|owner| owner.id == source.id));
            let message = match owner {
                Some(owner) => Some(format!("Command `{}` already registered by {} ({})", command.id, owner.description["displayName"].as_str().or(owner.description["name"].as_str()).unwrap_or_default(), owner.id)),
                None if REFERENCE["menuCommands"].as_array().expect("an array").iter().any(|id| *id == command.id) => Some(format!("Command `{}` already registered", command.id)),
                None => None,
            };
            if let Some(message) = message {
                crate::perf::extension_point_message(&extension.id, Severity::Info, message);
            }
            commands.push(command);
        }
    }
    for extension in extensions {
        for entry in extension.description["contributes"]["menus"]["commandPalette"].as_array().into_iter().flatten() {
            // menusExtensionPoint.ts skips entries of commands nobody contributes.
            let Some(command) = entry["command"].as_str().and_then(|id| commands.iter().find(|command| command.id == id)) else { continue };
            let when = entry["when"].as_str().and_then(Expr::deserialize);
            items.push(MenuItem { when, ..command.clone() });
        }
    }
    for command in commands {
        if !items.iter().any(|item| item.id == command.id) {
            items.push(command);
        }
    }
    items
}

/// `contributes.commands` as `MenuRegistry.addCommand` gets them: the `enablement` is the precondition.
pub fn contributed_commands(extension: &ScannedExtension) -> Vec<MenuItem> {
    let commands = match &extension.description["contributes"]["commands"] {
        Value::Array(commands) => commands.iter().collect(),
        Value::Null => Vec::new(),
        command => vec![command],
    };
    let localized = |value: &Value| value.as_str().or_else(|| value["value"].as_str()).map(str::to_string);
    let mut items = Vec::new();
    for command in commands {
        if let Err(message) = validate_command(command) {
            crate::perf::extension_point_message(&extension.id, Severity::Error, message);
            continue;
        }
        let (Some(id), Some(title)) = (command["command"].as_str(), localized(&command["title"])) else { unreachable!("validate_command checked both") };
        items.push(MenuItem {
            id: id.to_string(),
            title,
            category: localized(&command["category"]),
            description: None,
            when: None,
            precondition: command["enablement"].as_str().and_then(Expr::deserialize),
            source: Some(ExtensionSource::of(extension)),
        });
    }
    items
}

/// menusExtensionPoint.ts `isValidCommand`; JSON null stands for undefined.
fn validate_command(command: &Value) -> Result<(), String> {
    let falsy_or_whitespace = |value: &Value| value.as_str().is_none_or(|text| text.trim().is_empty());
    let truthy = |value: &Value| match value {
        Value::Null | Value::Bool(false) => false,
        Value::Number(number) => number.as_f64() != Some(0.),
        Value::String(text) => !text.is_empty(),
        _ => true,
    };
    let localized_string = |value: &Value, property: &str| match value {
        Value::Null => Err(format!("property `{property}` is mandatory and must be of type `string` or `object`")),
        Value::String(_) if falsy_or_whitespace(value) => Err(format!("property `{property}` is mandatory and must be of type `string`")),
        Value::String(_) => Ok(()),
        _ if falsy_or_whitespace(&value["original"]) || falsy_or_whitespace(&value["value"]) => Err(format!("properties `{property}.value` and `{property}.original` are mandatory and must be of type `string`")),
        _ => Ok(()),
    };
    if !truthy(command) {
        return Err("expected non-empty value.".into());
    }
    if falsy_or_whitespace(&command["command"]) {
        return Err("property `command` is mandatory and must be of type `string`".into());
    }
    localized_string(&command["title"], "title")?;
    if truthy(&command["shortTitle"]) {
        localized_string(&command["shortTitle"], "shortTitle")?;
    }
    if truthy(&command["enablement"]) && !command["enablement"].is_string() {
        return Err("property `precondition` can be omitted or must be of type `string`".into());
    }
    if truthy(&command["category"]) {
        localized_string(&command["category"], "category")?;
    }
    let icon = &command["icon"];
    if !icon.is_null() && !icon.is_string() && !(icon["dark"].is_string() && icon["light"].is_string()) {
        return Err("property `icon` can be omitted or must be either a string or a literal like `{dark, light}`".into());
    }
    Ok(())
}

/// `getGlobalCommandPicks`: the items whose `when` holds and that are enabled, labelled "Category: Title".
/// A workbench item shows only when the port registers its command.
pub fn enabled_commands(menu: &[MenuItem], context: &dyn Context, commands: &Commands) -> Vec<CommandPick> {
    let holds = |expr: &Option<Expr>| expr.as_ref().is_none_or(|expr| expr.evaluate(context));
    let mut picks = Vec::new();
    for item in menu {
        if (item.source.is_none() && commands.get(&item.id).is_none()) || !holds(&item.when) || !holds(&item.precondition) {
            continue;
        }
        picks.push(CommandPick { id: item.id.clone(), label: strip_icons(&item.label()), category: item.category.clone(), description: item.description.clone() });
    }
    picks
}

/// The `EditorAction`s of the active editor this port runs, by id, label and precondition (findController.ts,
/// folding.ts, multicursor.ts, linesOperations.ts, indentation.ts, comment.ts).
pub const EDITOR_ACTIONS: &[(&str, &str, Option<&str>)] = &[
    ("editor.unfold", "Unfold", Some("foldingEnabled")),
    ("editor.unfoldRecursively", "Unfold Recursively", Some("foldingEnabled")),
    ("editor.fold", "Fold", Some("foldingEnabled")),
    ("editor.toggleFold", "Toggle Fold", Some("foldingEnabled")),
    ("editor.foldRecursively", "Fold Recursively", Some("foldingEnabled")),
    ("editor.toggleFoldRecursively", "Toggle Fold Recursively", Some("foldingEnabled")),
    ("editor.foldAllBlockComments", "Fold All Block Comments", Some("foldingEnabled")),
    ("editor.foldAllMarkerRegions", "Fold All Regions", Some("foldingEnabled")),
    ("editor.unfoldAllMarkerRegions", "Unfold All Regions", Some("foldingEnabled")),
    ("editor.foldAllExcept", "Fold All Except Selected", Some("foldingEnabled")),
    ("editor.unfoldAllExcept", "Unfold All Except Selected", Some("foldingEnabled")),
    ("editor.foldAll", "Fold All", Some("foldingEnabled")),
    ("editor.unfoldAll", "Unfold All", Some("foldingEnabled")),
    ("editor.gotoParentFold", "Go to Parent Fold", Some("foldingEnabled")),
    ("editor.gotoPreviousFold", "Go to Previous Folding Range", Some("foldingEnabled")),
    ("editor.gotoNextFold", "Go to Next Folding Range", Some("foldingEnabled")),
    ("editor.createFoldingRangeFromSelection", "Create Folding Range from Selection", Some("foldingEnabled")),
    ("editor.removeManualFoldingRanges", "Remove Manual Folding Ranges", Some("foldingEnabled")),
    ("editor.toggleImportFold", "Toggle Import Fold", Some("foldingEnabled")),
    ("editor.foldLevel1", "Fold Level 1", Some("foldingEnabled")),
    ("editor.foldLevel2", "Fold Level 2", Some("foldingEnabled")),
    ("editor.foldLevel3", "Fold Level 3", Some("foldingEnabled")),
    ("editor.foldLevel4", "Fold Level 4", Some("foldingEnabled")),
    ("editor.foldLevel5", "Fold Level 5", Some("foldingEnabled")),
    ("editor.foldLevel6", "Fold Level 6", Some("foldingEnabled")),
    ("editor.foldLevel7", "Fold Level 7", Some("foldingEnabled")),
    ("editor.action.insertCursorAbove", "Add Cursor Above", None),
    ("editor.action.insertCursorBelow", "Add Cursor Below", None),
    ("editor.action.insertCursorAtEndOfEachLineSelected", "Add Cursors to Line Ends", None),
    ("editor.action.addCursorsToBottom", "Add Cursors to Bottom", None),
    ("editor.action.addCursorsToTop", "Add Cursors to Top", None),
    ("editor.action.focusNextCursor", "Focus Next Cursor", None),
    ("editor.action.focusPreviousCursor", "Focus Previous Cursor", None),
    ("editor.action.addSelectionToNextFindMatch", "Add Selection to Next Find Match", None),
    ("editor.action.addSelectionToPreviousFindMatch", "Add Selection to Previous Find Match", None),
    ("editor.action.moveSelectionToNextFindMatch", "Move Last Selection to Next Find Match", None),
    ("editor.action.moveSelectionToPreviousFindMatch", "Move Last Selection to Previous Find Match", None),
    ("editor.action.selectHighlights", "Select All Occurrences of Find Match", None),
    ("editor.action.resetSuggestSize", "Reset Suggest Widget Size", None),
    ("editor.action.changeAll", "Change All Occurrences", Some("!editorReadonly && editorTextFocus")),
    ("editor.action.rename", "Rename Symbol", Some("!editorReadonly && editorHasRenameProvider")),
    ("editor.action.linkedEditing", "Start Linked Editing", Some("!editorReadonly && editorHasRenameProvider")),
    ("editor.inlayHints.Reset", "Reset Language Status Interaction Counter", None),
    ("editor.action.formatDocument", "Format Document", Some("!inCompositeEditor && !editorReadonly && editorHasDocumentFormattingProvider")),
    ("editor.action.formatSelection", "Format Selection", Some("!editorReadonly && editorHasDocumentSelectionFormattingProvider")),
    ("editor.action.formatDocument.multiple", "Format Document With...", Some("!editorReadonly && editorHasMultipleDocumentFormattingProvider")),
    ("editor.action.formatSelection.multiple", "Format Selection With...", Some("!editorReadonly && editorHasMultipleDocumentSelectionFormattingProvider")),
    ("editor.action.formatDocument.none", "Format Document", Some("!editorReadonly && !editorHasDocumentFormattingProvider")),
    ("editor.action.formatChanges", "Format Modified Lines", Some("!editorReadonly && editorHasDocumentSelectionFormattingProvider")),
    ("editor.action.indentationToSpaces", "Convert Indentation to Spaces", Some("!editorReadonly")),
    ("editor.action.indentationToTabs", "Convert Indentation to Tabs", Some("!editorReadonly")),
    ("editor.action.indentUsingTabs", "Indent Using Tabs", None),
    ("editor.action.indentUsingSpaces", "Indent Using Spaces", None),
    ("editor.action.changeTabDisplaySize", "Change Tab Display Size", None),
    ("editor.action.detectIndentation", "Detect Indentation from Content", None),
    ("editor.action.reindentlines", "Reindent Lines", Some("!editorReadonly")),
    ("editor.action.smartSelect.expand", "Expand Selection", None),
    ("editor.action.smartSelect.shrink", "Shrink Selection", None),
    // copyPasteContribution.ts
    ("editor.action.pasteAs", "Paste As...", Some("!editorReadonly")),
    ("editor.action.pasteAsText", "Paste as Text", Some("!editorReadonly")),
    ("cursorUndo", "Cursor Undo", None),
    ("cursorRedo", "Cursor Redo", None),
    ("editor.action.reindentselectedlines", "Reindent Selected Lines", Some("!editorReadonly")),
    ("editor.action.trimTrailingWhitespace", "Trim Trailing Whitespace", Some("!editorReadonly")),
    ("editor.action.insertFinalNewLine", "Insert Final New Line", Some("!editorReadonly")),
    ("deleteAllLeft", "Delete All Left", Some("!editorReadonly")),
    ("deleteAllRight", "Delete All Right", Some("!editorReadonly")),
    ("editor.action.copyLinesUpAction", "Copy Line Up", Some("!editorReadonly")),
    ("editor.action.copyLinesDownAction", "Copy Line Down", Some("!editorReadonly")),
    ("editor.action.duplicateSelection", "Duplicate Selection", Some("!editorReadonly")),
    ("editor.action.moveLinesUpAction", "Move Line Up", Some("!editorReadonly")),
    ("editor.action.moveLinesDownAction", "Move Line Down", Some("!editorReadonly")),
    ("editor.action.sortLinesAscending", "Sort Lines Ascending", Some("!editorReadonly")),
    ("editor.action.sortLinesDescending", "Sort Lines Descending", Some("!editorReadonly")),
    ("editor.action.removeDuplicateLines", "Delete Duplicate Lines", Some("!editorReadonly")),
    ("editor.action.reverseLines", "Reverse lines", Some("!editorReadonly")),
    ("editor.action.deleteLines", "Delete Line", Some("!editorReadonly")),
    ("editor.action.indentLines", "Indent Line", Some("!editorReadonly")),
    ("editor.action.outdentLines", "Outdent Line", Some("!editorReadonly")),
    ("editor.action.insertLineBefore", "Insert Line Above", Some("!editorReadonly")),
    ("editor.action.insertLineAfter", "Insert Line Below", Some("!editorReadonly")),
    ("editor.action.joinLines", "Join Lines", Some("!editorReadonly")),
    ("editor.action.transpose", "Transpose Characters around the Cursor", Some("!editorReadonly")),
    ("expandLineSelection", "Expand Line Selection", None),
    ("editor.action.inPlaceReplace.up", "Replace with Previous Value", Some("!editorReadonly")),
    ("editor.action.inPlaceReplace.down", "Replace with Next Value", Some("!editorReadonly")),
    ("editor.action.moveCarretLeftAction", "Move Selected Text Left", Some("!editorReadonly")),
    ("editor.action.moveCarretRightAction", "Move Selected Text Right", Some("!editorReadonly")),
    ("editor.action.transposeLetters", "Transpose Letters", Some("!editorReadonly")),
    ("editor.action.setSelectionAnchor", "Set Selection Anchor", None),
    ("editor.action.goToSelectionAnchor", "Go to Selection Anchor", Some("selectionAnchorSet")),
    ("editor.action.selectFromAnchorToCursor", "Select from Anchor to Cursor", Some("selectionAnchorSet")),
    ("editor.action.cancelSelectionAnchor", "Cancel Selection Anchor", Some("selectionAnchorSet")),
    ("editor.action.fontZoomIn", "Increase Editor Font Size", None),
    ("editor.action.toggleTabFocusMode", "Toggle Tab Key Moves Focus", None),
    ("editor.action.fontZoomOut", "Decrease Editor Font Size", None),
    ("editor.action.fontZoomReset", "Reset Editor Font Size", None),
    ("editor.action.transformToUppercase", "Transform to Uppercase", Some("!editorReadonly")),
    ("editor.action.transformToLowercase", "Transform to Lowercase", Some("!editorReadonly")),
    ("editor.action.transformToTitlecase", "Transform to Title Case", Some("!editorReadonly")),
    ("editor.action.transformToSnakecase", "Transform to Snake Case", Some("!editorReadonly")),
    ("editor.action.transformToCamelcase", "Transform to Camel Case", Some("!editorReadonly")),
    ("editor.action.transformToPascalcase", "Transform to Pascal Case", Some("!editorReadonly")),
    ("editor.action.transformToKebabcase", "Transform to Kebab Case", Some("!editorReadonly")),
    ("actions.find", "Find", Some("editorFocus || editorIsOpen")),
    ("editor.actions.findWithArgs", "Find with Arguments", None),
    ("actions.findWithSelection", "Find with Selection", None),
    ("editor.action.nextMatchFindAction", "Find Next", None),
    ("editor.action.previousMatchFindAction", "Find Previous", None),
    ("editor.action.goToMatchFindAction", "Go to Match...", Some("findWidgetVisible")),
    ("editor.action.nextSelectionMatchFindAction", "Find Next Selection", None),
    ("editor.action.previousSelectionMatchFindAction", "Find Previous Selection", None),
    ("editor.action.startFindReplaceAction", "Replace", Some("editorFocus || editorIsOpen")),
    ("editor.action.commentLine", "Toggle Line Comment", Some("!editorReadonly")),
    ("editor.action.addCommentLine", "Add Line Comment", Some("!editorReadonly")),
    ("editor.action.removeCommentLine", "Remove Line Comment", Some("!editorReadonly")),
    ("editor.action.blockComment", "Toggle Block Comment", Some("!editorReadonly")),
    ("editor.action.revealDefinition", "Go to Definition", Some("editorHasDefinitionProvider")),
    ("editor.action.revealDefinitionAside", "Open Definition to the Side", Some("editorHasDefinitionProvider && !isInEmbeddedEditor")),
    ("editor.action.peekDefinition", "Peek Definition", Some("editorHasDefinitionProvider && !inReferenceSearchEditor && !isInEmbeddedEditor")),
    ("editor.action.revealDeclaration", "Go to Declaration", Some("editorHasDeclarationProvider && !isInEmbeddedEditor")),
    ("editor.action.peekDeclaration", "Peek Declaration", Some("editorHasDeclarationProvider && !inReferenceSearchEditor && !isInEmbeddedEditor")),
    ("editor.action.goToTypeDefinition", "Go to Type Definition", Some("editorHasTypeDefinitionProvider")),
    ("editor.action.peekTypeDefinition", "Peek Type Definition", Some("editorHasTypeDefinitionProvider && !inReferenceSearchEditor && !isInEmbeddedEditor")),
    ("editor.action.goToImplementation", "Go to Implementations", Some("editorHasImplementationProvider")),
    ("editor.action.peekImplementation", "Peek Implementations", Some("editorHasImplementationProvider && !inReferenceSearchEditor && !isInEmbeddedEditor")),
    ("editor.action.goToReferences", "Go to References", Some("editorHasReferenceProvider && !inReferenceSearchEditor && !isInEmbeddedEditor")),
    ("editor.action.referenceSearch.trigger", "Peek References", Some("editorHasReferenceProvider && !inReferenceSearchEditor && !isInEmbeddedEditor")),
    ("editor.action.showDefinitionPreviewHover", "Show Definition Preview Hover", None),
    ("editor.action.marker.next", "Go to Next Problem (Error, Warning, Info)", None),
    ("editor.action.marker.prev", "Go to Previous Problem (Error, Warning, Info)", None),
    ("editor.action.marker.nextInFiles", "Go to Next Problem in Files (Error, Warning, Info)", None),
    ("editor.action.marker.prevInFiles", "Go to Previous Problem in Files (Error, Warning, Info)", None),
    ("editor.action.inspectTMScopes", "Developer: Inspect Editor Tokens and Scopes", None),
];

/// `getCodeEditorCommandPicks`: the active editor's supported actions, those whose precondition holds.
pub fn editor_action_picks(context: &dyn Context) -> Vec<CommandPick> {
    let mut picks = Vec::new();
    for (id, label, precondition) in EDITOR_ACTIONS {
        if precondition.and_then(Expr::deserialize).is_none_or(|expr| expr.evaluate(context)) {
            picks.push(CommandPick { id: id.to_string(), label: label.to_string(), category: None, description: None });
        }
    }
    picks
}

/// `stripIcons`: replaces each `(\s)?(\\)?$(name~modifier)(\s)?` by the whitespace before it, else the one
/// after it; an escaped `\$(name)` stays.
pub fn strip_icons(label: &str) -> String {
    let mut stripped = String::new();
    let mut rest = label;
    while let Some(start) = rest.find("$(") {
        let Some(length) = icon_length(&rest[start..]) else {
            stripped.push_str(&rest[..start + 2]);
            rest = &rest[start + 2..];
            continue;
        };
        if rest[..start].ends_with('\\') {
            stripped.push_str(&rest[..start + length]);
            rest = &rest[start + length..];
            continue;
        }
        let before = rest[..start].chars().next_back().filter(|c| c.is_whitespace());
        stripped.push_str(&rest[..start - before.map_or(0, char::len_utf8)]);
        rest = &rest[start + length..];
        let after = rest.chars().next().filter(|c| c.is_whitespace());
        rest = &rest[after.map_or(0, char::len_utf8)..];
        if let Some(whitespace) = before.or(after) {
            stripped.push(whitespace);
        }
    }
    stripped.push_str(rest);
    stripped
}

/// Length of the `$([A-Za-z0-9-]+(~[A-Za-z]+)?)` at the start of `text`.
fn icon_length(text: &str) -> Option<usize> {
    let inner = &text[2..];
    let end = inner.find(')')?;
    let (name, modifier) = inner[..end].split_once('~').map_or((&inner[..end], None), |(name, modifier)| (name, Some(modifier)));
    let name_ok = !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-');
    let modifier_ok = modifier.is_none_or(|modifier| !modifier.is_empty() && modifier.chars().all(|c| c.is_ascii_alphabetic()));
    (name_ok && modifier_ok).then_some(2 + end + 1)
}

/// `or(matchesBaseContiguousSubString, matchesWords)`.
pub fn word_filter(filter: &str, label: &str) -> Option<Matches> {
    matches_base_contiguous_sub_string(filter, label).or_else(|| matches_words(filter, label))
}

fn tf_idf(commands: &[CommandPick], filter: &str) -> Vec<crate::tf_idf::Score> {
    let mut calculator = TfIdfCalculator::default();
    calculator.update_documents(commands.iter().map(|command| Document { key: command.id.clone(), text_chunks: vec![tf_idf_chunk(command)] }).collect());
    let mut scores = normalize_scores(calculator.calculate_scores(filter));
    scores.retain(|score| score.score > TFIDF_THRESHOLD);
    scores.truncate(TFIDF_MAX_RESULTS);
    scores
}

/// `getTfIdfChunk`: the label, then the description when it is not the label.
fn tf_idf_chunk(command: &CommandPick) -> String {
    match &command.description {
        Some(description) if *description != command.label => format!("{} - {description}", command.label),
        _ => command.label.clone(),
    }
}

/// TF-IDF matches last, then most recently used, then not Developer commands, then by label.
fn compare(a: &Candidate, b: &Candidate, history: &CommandsHistory) -> Ordering {
    match (a.tf_idf_score, b.tf_idf_score) {
        (Some(a_score), Some(b_score)) if a_score == b_score => return locale_compare(&a.command.label, &b.command.label),
        (Some(a_score), Some(b_score)) => return b_score.total_cmp(&a_score),
        (Some(_), None) => return Ordering::Greater,
        (None, Some(_)) => return Ordering::Less,
        (None, None) => {}
    }
    match (history.peek(&a.command.id), history.peek(&b.command.id)) {
        (Some(a_counter), Some(b_counter)) => return b_counter.cmp(&a_counter),
        (Some(_), None) => return Ordering::Less,
        (None, Some(_)) => return Ordering::Greater,
        (None, None) => {}
    }
    let is_developer = |candidate: &Candidate| candidate.command.category.as_deref() == Some("Developer");
    match (is_developer(a), is_developer(b)) {
        (true, false) => Ordering::Greater,
        (false, true) => Ordering::Less,
        _ => locale_compare(&a.command.label, &b.command.label),
    }
}

/// `String.prototype.localeCompare` in English: accents and case only break ties, lower case first, and
/// whitespace, punctuation and symbols sort before digits and letters.
/// A few rules of the ICU root collation, which Rust std lacks.
pub fn locale_compare(a: &str, b: &str) -> Ordering {
    // ICU root collation order of ASCII punctuation and symbols (node: `.sort((a, b) => a.localeCompare(b))`).
    const ASCII_SYMBOLS: &str = "_-,;:!?.'\"()[]{}@*/\\&#%`^+<=>|~$";
    let primary = |text: &str| -> Vec<(u8, u32)> {
        try_normalize_to_base(text)
            .chars()
            .map(|c| {
                if let Some(rank) = ASCII_SYMBOLS.find(c) {
                    return (1, rank as u32);
                }
                let class = if c.is_whitespace() {
                    0
                } else if c.is_numeric() {
                    3
                } else if c.is_alphabetic() {
                    4
                } else {
                    2
                };
                (class, c as u32)
            })
            .collect()
    };
    let case = |text: &str| -> Vec<bool> { text.chars().map(char::is_uppercase).collect() };
    primary(a).cmp(&primary(b)).then_with(|| case(a).cmp(&case(b))).then_with(|| a.cmp(b))
}

#[cfg(test)]
mod tests;