Skip to content

Visual Studio Code, rebuilt in Rust

Rust
45.7 KB
Raw Blame
//! The MainThread* requests the session thread blocks on: mainThreadDocuments.ts, mainThreadEditors.ts with
//! mainThreadEditor.ts. `main_thread_commands.rs::route` names them; they arrive through `main_thread.rs`.

use std::path::{Path, PathBuf};
use std::time::Instant;

use config::configuration::Overrides;
use config::indentation::creation_options;
use exthost::main_thread::serialized_error;
use exthost::main_thread_files::resource;
use exthost::settings_file_system;
use files::encoding;
use gpui::{Context, Window};
use serde_json::{Value, json};

use super::Workbench;
use super::auto_save::SaveReason;
use super::bulk_text_edits::document_end;
use super::snippet_controller::SnippetInsert;
use super::model_events::Cursor;
use crate::editor::Reveal;
use crate::editor::{
    CursorEdit, EditReason, OpenEditor, Position, Replace, Selection, SnippetText, TextDocument, VerticalReveal, char_column, end_of, expand_snippet,
    on_disk, selections_after, text_between, uri_string,
};
use crate::commands::Outcome;
use crate::editor::decoration_types::TextDecoration;
use crate::editor::injected_text::InjectionOwner;
use crate::languages::Languages;
use crate::host_sync::snapshot_id;

#[cfg(test)]
mod tests;

type HostResult = Result<Value, Value>;

impl Workbench {
    pub(crate) fn remove_decoration_type(&mut self, key: &str, cx: &mut Context<Self>) {
        self.editors.decoration_types.remove(key);
        for editor in self.editors.all_editors_mut() {
            editor.text_decorations.retain(|decoration| decoration.key != key);
        }
        let content: Vec<_> = self.editors.all_editors().map(|editor| self.decoration_content_text(editor)).collect();
        for (editor, injections) in self.editors.all_editors_mut().zip(content) {
            editor.set_injected_text(InjectionOwner::DecorationContent, injections);
        }
        cx.notify();
    }

    /// The group whose active editor is the host's text editor `id`.
    fn host_editor_group(&self, id: &str) -> Option<u32> {
        self.groups_in_grid_order().into_iter().find(|&group| self.editors.group_active(group).is_some_and(|(editor, _)| snapshot_id(editor) == id))
    }

    // mainThreadEditors.ts: an editor the host no longer has is left alone, without an error.
    pub(crate) fn show_host_editor(&mut self, args: &[Value], window: &mut Window, cx: &mut Context<Self>) -> HostResult {
        let Some(group) = self.host_editor_group(args[0].as_str().unwrap_or_default()) else { return Ok(Value::Null) };
        let uri = self.editors.group_active(group).expect("found above").0.document().uri();
        let position = args.get(1).cloned().unwrap_or(Value::Null);
        self.try_show_text_document(&uri, &json!({ "position": position, "preserveFocus": false }), window, cx)?;
        Ok(Value::Null)
    }

    pub(crate) fn hide_host_editor(&mut self, args: &[Value], window: &mut Window, cx: &mut Context<Self>) -> HostResult {
        let Some(group) = self.host_editor_group(args[0].as_str().unwrap_or_default()) else { return Ok(Value::Null) };
        self.focus_group(group, window, cx);
        let index = self.editors.active_index().expect("the group shows the editor");
        // shortcut: answers before a dirty editor's save prompt closes it, upstream awaits closeEditor; route through the forwarded requests if an extension awaits it.
        drop(self.close_editors(vec![index], window, cx));
        Ok(Value::Null)
    }

    /// Runs `run` with the host's text editor `args[0]` active: a group's active editor or a peek widget's editor.
    pub(crate) fn with_host_editor(&mut self, args: &[Value], run: impl FnOnce(&mut Self) -> HostResult) -> HostResult {
        let id = args[0].as_str().unwrap_or_default();
        let group = self.host_editor_group(id);
        let peek = self.editors.peek_editors.iter().map(|peek| &peek.editor).find(|editor| snapshot_id(editor) == id).map(|editor| editor.model_id);
        match (group, peek) {
            (Some(group), _) => self.with_group(group, run),
            (None, Some(peek)) => self.with_code_editor(peek, run),
            (None, None) => Err(serialized_error(&format!("Illegal argument: TextEditor({id})"))),
        }
    }

    pub(crate) fn set_host_decorations(&mut self, key: &str, decorations: Vec<TextDecoration>, cx: &mut Context<Self>) -> HostResult {
        let editor = self.editors.active_mut().expect("with_host_editor made it active");
        editor.text_decorations.retain(|decoration| decoration.key != key);
        editor.text_decorations.extend(decorations);
        let injections = self.decoration_content_text(self.editors.active().expect("found above"));
        self.editors.active_mut().expect("found above").set_injected_text(InjectionOwner::DecorationContent, injections);
        cx.notify();
        Ok(Value::Null)
    }

    /// `BoundModelReferenceCollection`: models the host opened and no editor shows are disposed after 3 minutes.
    pub(crate) fn release_host_models(&mut self, cx: &mut Context<Self>) {
        let count = self.editors.models.len();
        let scm_inputs = self.scm_input_models();
        // A notebook cell's text model lives as long as its notebook, a playground snippet's as long as the playground.
        let playground_open = self.playground_open();
        let next_expiry = self.editors.release_models_except(Instant::now(), |model| {
            let scheme = model.document().scheme.clone();
            matches!(scheme.as_str(), crate::notebook::CELL_SCHEME | super::interactive::INPUT_SCHEME | super::comments::INPUT_SCHEME)
                || (playground_open && scheme == super::walkthrough_part::SNIPPET_SCHEME)
                || scm_inputs.iter().any(|(scheme, path)| model.document().is(scheme, path))
        });
        if self.editors.models.len() != count {
            self.editors_changed(cx);
        }
        self.schedule_host_model_release(next_expiry, cx);
    }

    /// The `setTimeout` of `BoundModelReferenceCollection.add`: the models go when their reference expires, without
    /// waiting for the next host call.
    fn schedule_host_model_release(&mut self, next_expiry: Option<Instant>, cx: &mut Context<Self>) {
        let Some(next_expiry) = next_expiry else {
            self.host_model_release = None;
            return;
        };
        if self.host_model_release.as_ref().is_some_and(|(scheduled, _)| *scheduled == next_expiry) {
            return;
        }
        let task = cx.spawn(async move |workbench, cx| {
            cx.background_executor().timer(next_expiry.saturating_duration_since(Instant::now())).await;
            let _ = workbench.update(cx, |workbench, cx| {
                workbench.host_model_release = None;
                workbench.release_host_models(cx);
            });
        });
        self.host_model_release = Some((next_expiry, task));
    }

    /// `$tryOpenDocument`: the model of a file, of the bytes an extension's file system provider read
    /// (`provider_content` an array) or of a content provider's text (a string), opened without an editor and kept
    /// while the host references it. `options.encoding` decodes a new model, or a clean open one again.
    pub(crate) fn try_open_document(&mut self, uri: &Value, options: &Value, provider_content: &Value, ignore_path_case: bool, cx: &mut Context<Self>) -> HostResult {
        let (scheme, ref path) = uri_parts(uri)?;
        // uriIdentityService.ts `asCanonicalUri`: where the provider ignores path case, the casing opened first wins.
        if ignore_path_case {
            let lowercase = path.to_string_lossy().to_lowercase();
            let first_casing = self.editors.all_editors().map(|model| model.document()).find(|document| document.scheme == scheme && document.path != *path && document.path.to_string_lossy().to_lowercase() == lowercase).map(|document| document.uri());
            if let Some(uri) = first_casing {
                return self.try_open_document(&uri, options, provider_content, false, cx);
            }
        }
        let requested = options["encoding"].as_str();
        if let Some(model) = self.editors.model_mut(scheme, path) {
            model.text_model_mut().add_host_reference(Instant::now());
            if let Some(requested) = requested {
                let provider_bytes = provider_content.is_array().then(|| serde_json::from_value(provider_content.clone()).expect("bytes from main_thread.rs"));
                self.set_model_encoding(uri, scheme, path, requested, provider_bytes, cx)
                    .map_err(|detail| serialized_error(&format!("cannot open {}. Detail: {detail}", uri_string(scheme, path))))?;
            }
            return Ok(uri.clone());
        }
        let document = match (scheme, provider_content) {
            (_, Value::Array(_)) => {
                let bytes: Vec<u8> = serde_json::from_value(provider_content.clone()).expect("bytes from main_thread.rs");
                TextDocument::from_bytes(scheme, path, &bytes, requested, &self.languages, &self.settings.lock().unwrap())
            }
            (_, Value::String(text)) => TextDocument::from_text(scheme, path, text, encoding::UTF8.into(), None, &self.languages, &self.settings.lock().unwrap()),
            (scheme, _) if on_disk(scheme) => {
                let bytes = std::fs::read(path)
                    .map_err(|error| serialized_error(&format!("cannot open {}. Detail: Unable to read file '{}' ({error})", uri_string(scheme, path), path.display())))?;
                TextDocument::from_bytes(scheme, path, &bytes, requested, &self.languages, &self.settings.lock().unwrap())
            }
            // mainThreadDocuments.ts `_handleUntitledScheme`: an untitled model for the path, never over an existing file.
            ("untitled", _) if path.exists() => return Err(serialized_error(&format!("cannot open {}. Detail: file already exists", uri_string(scheme, path)))),
            ("untitled", _) => {
                let mut document = TextDocument::untitled(path, "", None, &self.languages, &self.settings.lock().unwrap());
                document.encoding = requested.map_or(document.encoding, str::to_string);
                document
            }
            ("vscode", _) => {
                let default_settings = self.preferences_content(path);
                let bytes = settings_file_system::read_file(&self.settings.lock().unwrap(), &resource(uri), default_settings)
                    .map_err(|error| serialized_error(&format!("cannot open {}. Detail: {error}", uri_string(scheme, path))))?;
                let text = String::from_utf8(bytes).expect("schemas and default settings are JSON text");
                TextDocument::from_text(scheme, path, &text, encoding::UTF8.into(), None, &self.languages, &self.settings.lock().unwrap())
            }
            // textModelResolverService.ts `ensureResolvedTextModelContent`: an inmemory resource resolves only to a model it has.
            ("inmemory", _) => {
                let uri = uri_string(scheme, path);
                return Err(serialized_error(&format!("cannot open {uri}. Detail: Unable to resolve text model content for resource {uri}")));
            }
            _ => return Err(serialized_error(&format!("cannot open {scheme}:{}. Detail: Unable to resolve resource {scheme}:{}", path.display(), path.display()))),
        };
        let index = self.editors.open_model(document);
        let model = &mut self.editors.models[index];
        model.text_model_mut().add_host_reference(Instant::now());
        model.text_model_mut().associated_file = scheme == "untitled";
        self.editors_changed(cx);
        // `_handleUntitledScheme` ends in `_doCreateUntitled`, which marks the host's document dirty.
        if scheme == "untitled" {
            self.host.send("ExtHostDocuments", "$acceptDirtyStateChanged", vec![uri.clone(), json!(true)]);
        }
        Ok(uri.clone())
    }

    /// `setEncoding(encoding, EncodingMode.Decode)` of an open model: an untitled model takes the encoding, a clean
    /// file model is read again in it (`forceResolveFromFile`) and takes the encoding the read settled on. A model of an
    /// extension's file system provider is decoded from `provider_bytes`, which the session thread read through it.
    pub(super) fn set_model_encoding(&mut self, uri: &Value, scheme: &str, path: &Path, requested: &str, provider_bytes: Option<Vec<u8>>, cx: &mut Context<Self>) -> Result<(), String> {
        let model = self.editors.model_mut(scheme, path).expect("the caller found the model");
        if model.document().encoding == requested {
            return Ok(());
        }
        if scheme == "untitled" {
            model.document_mut().encoding = requested.to_string();
            self.host.send("ExtHostDocuments", "$acceptEncodingChanged", vec![uri.clone(), json!(requested)]);
            return Ok(());
        }
        if model.is_dirty() {
            return Err("Cannot re-open a dirty text document with different encoding. Save it first.".into());
        }
        let bytes = match on_disk(scheme) {
            true => Some(std::fs::read(path).map_err(|error| format!("Unable to read file '{}' ({error})", path.display()))?),
            false => provider_bytes,
        };
        let settings = self.settings.lock().unwrap();
        let resource = on_disk(scheme).then_some(path);
        let detected = bytes.as_deref().and_then(|bytes| crate::encoding_guess::detect(bytes, &settings, resource, false));
        let language = model.document().language_id.clone();
        let resolved = encoding::read_encoding(&settings, &Overrides { resource, override_identifier: Some(&language) }, Some(requested), detected.as_deref());
        drop(settings);
        if model.document().encoding != resolved {
            model.document_mut().encoding = resolved.clone();
            self.host.send("ExtHostDocuments", "$acceptEncodingChanged", vec![uri.clone(), json!(resolved)]);
        }
        if let Some(bytes) = bytes {
            self.replace_model_text(scheme, path, encoding::decode(&bytes, &resolved), true, cx);
        }
        Ok(())
    }

    /// `PreferencesService.getDefaultSettingsContent` for the extension host's `vscode://defaultsettings` reads; null
    /// for any other resource.
    pub(crate) fn default_settings_content(&self, uri: &Value) -> Value {
        uri_parts(uri).ok().and_then(|(_, path)| self.preferences_content(&path)).map_or(Value::Null, Value::String)
    }

    /// textFileService.ts `resolveDecoding`, `validateDetectedEncoding` and `resolveEncoding`, which the extension host
    /// asks for `workspace.decode` and `workspace.encode`. Settings are read for the open model's language, else the
    /// language of the path (textResourceConfiguration.ts `getLanguage`).
    pub(crate) fn resolve_text_file_encoding(&self, method: &str, uri: &Value, second: &Value, third: &Value) -> Value {
        let parts = uri_parts(uri).ok();
        let settings = self.settings.lock().unwrap();
        let language = parts.as_ref().and_then(|(scheme, path)| match self.editors.model(scheme, path) {
            Some(model) => Some(model.document().language_id.clone()),
            None => crate::editor::language_of_path(scheme, path, &self.languages, &settings),
        });
        let resource = parts.as_ref().filter(|(scheme, _)| *scheme == "file").map(|(_, path)| path.as_path());
        let overrides = Overrides { resource, override_identifier: language.as_deref() };
        let setting = |key| settings.get_value(Some(key), &overrides).unwrap_or(Value::Null);
        match method {
            "$resolveDecoding" => json!({
                "preferredEncoding": encoding::read_encoding(&settings, &overrides, second["encoding"].as_str(), None),
                "guessEncoding": setting("files.autoGuessEncoding"),
                "candidateGuessEncodings": setting("files.candidateGuessEncodings"),
            }),
            "$validateDetectedEncoding" => json!(encoding::read_encoding(&settings, &overrides, third["encoding"].as_str(), second.as_str())),
            _ => {
                let (encoding, add_bom) = encoding::write_encoding(&settings, &overrides, second["encoding"].as_str());
                json!({ "encoding": encoding, "addBOM": add_bom })
            }
        }
    }

    /// mainThreadLanguages.ts `$changeLanguage`: a registered language for the model, opened when needed.
    pub(crate) fn change_host_language(&mut self, uri: &Value, language_id: &Value, cx: &mut Context<Self>) -> HostResult {
        let language_id = language_id.as_str().unwrap_or_default();
        if !self.languages.is_registered(language_id) {
            return Err(serialized_error(&format!("Unknown language id: {language_id}")));
        }
        let (scheme, ref path) = uri_parts(uri)?;
        if self.editors.model(scheme, path).is_none() {
            self.try_open_document(uri, &Value::Null, &Value::Null, false, cx)?;
        }
        self.text_files.preferred_languages.insert((scheme.to_string(), path.clone()));
        self.set_model_language(scheme, path, language_id, cx);
        Ok(Value::Null)
    }

    /// mainThreadLanguages.ts `$tokensAtPosition`: the standard type and range of the token at the position, none
    /// for a model that is not open.
    pub(crate) fn tokens_at_position(&self, scheme: &str, path: &Path, position: &Value) -> Value {
        let Some(editor) = self.editors.model(scheme, path) else { return Value::Null };
        let document = editor.document();
        let line_number = position["lineNumber"].as_u64().unwrap_or(1) as usize;
        let Some(line) = document.lines.get(line_number.saturating_sub(1)) else { return Value::Null };
        let index = line_number - 1;
        let column = crate::editor::char_column(line, (position["column"].as_u64().unwrap_or(1) as usize).saturating_sub(1));
        let offset = line.char_indices().nth(column).map_or(line.len(), |(offset, _)| offset);
        let mut start = 0;
        for (end, token_type, _) in document.tokens.line_tokens(&document.lines, index) {
            if end > offset || end >= line.len() {
                let utf16 = |byte: usize| line[..byte.min(line.len())].encode_utf16().count() + 1;
                return json!({ "type": token_type as u8, "range": { "startLineNumber": line_number, "startColumn": utf16(start), "endLineNumber": line_number, "endColumn": utf16(end) } });
            }
            start = end;
        }
        Value::Null
    }

    /// `$computeFullSyntaxHighlighting`: the source's TextMate tokens in the language (by id or name) as UTF-16 lengths
    /// with their theme foreground index and font style, a 1-long token per newline, and the theme's color map.
    pub(crate) fn full_syntax_highlighting(&self, source: &str, language: &str) -> Value {
        let color_map: Vec<String> = self.theme.tokens.color_map().iter().map(|color| css_hex_alpha(color)).collect();
        let language = if self.languages.is_registered(language) { Some(language) } else { self.languages.id_by_name(language) };
        let Some(grammar) = language.and_then(|language| self.languages.grammars.grammar(language)) else {
            let tokens = if source.is_empty() { json!([]) } else { json!([{ "length": source.encode_utf16().count(), "foreground": 0, "fontStyle": 0 }]) };
            return json!({ "tokens": tokens, "colorMap": color_map });
        };
        let mut tokens: Vec<Value> = Vec::new();
        let mut state = None;
        let lines: Vec<&str> = source.split('\n').collect();
        for (index, line) in lines.iter().enumerate() {
            let Ok((line_tokens, next)) = grammar.tokenize_line(line, state.as_ref()) else { break };
            state = Some(next);
            // tokenizeLine2 emits a token where the metadata changes, so neighbors with one style are one token.
            let mut runs: Vec<(usize, usize, i32)> = Vec::new();
            for token in &line_tokens {
                let style = self.theme.tokens.style(&token.scopes);
                let font_style = style.font_style.max(0);
                let length = line[token.start.min(line.len())..token.end.min(line.len())].encode_utf16().count();
                match runs.last_mut() {
                    Some(last) if last.1 == style.foreground && last.2 == font_style => last.0 += length,
                    _ => runs.push((length, style.foreground, font_style)),
                }
            }
            tokens.extend(runs.into_iter().filter(|run| run.0 > 0).map(|(length, foreground, font_style)| json!({ "length": length, "foreground": foreground, "fontStyle": font_style })));
            if index + 1 < lines.len() {
                tokens.push(json!({ "length": 1, "foreground": 0, "fontStyle": 0 }));
            }
        }
        json!({ "tokens": tokens, "colorMap": color_map })
    }

    /// `$tryCreateDocument`: a new untitled model named `Untitled-<n>` with the first free n.
    pub(crate) fn try_create_document(&mut self, options: &Value, cx: &mut Context<Self>) -> HostResult {
        let path = (1..).map(|n| PathBuf::from(format!("Untitled-{n}"))).find(|path| self.editors.model("untitled", path).is_none()).expect("a free name");
        let content = options["content"].as_str().unwrap_or_default();
        let language = self.untitled_language(options["language"].as_str().map(str::to_string));
        let mut document = TextDocument::untitled(&path, content, language.as_deref(), &self.languages, &self.settings.lock().unwrap());
        document.encoding = options["encoding"].as_str().map_or(document.encoding, str::to_string);
        let uri = document.uri();
        let index = self.editors.open_model(document);
        self.editors.models[index].text_model_mut().add_host_reference(Instant::now());
        self.editors_changed(cx);
        // mainThreadDocuments.ts `_doCreateUntitled` tells the host the new document is dirty, whatever the model says.
        self.host.send("ExtHostDocuments", "$acceptDirtyStateChanged", vec![uri.clone(), json!(true)]);
        Ok(uri)
    }

    /// `$onVirtualDocumentChange`: a content provider's new text replaces the model's through `computeMoreMinimalEdits`,
    /// so the change events carry only the changed chars.
    pub(crate) fn virtual_document_change(&mut self, uri: &Value, value: &Value, cx: &mut Context<Self>) -> HostResult {
        let (scheme, ref path) = uri_parts(uri)?;
        let Some(model) = self.editors.model(scheme, path) else { return Ok(Value::Null) };
        let document = model.document();
        let whole = vec![(Position::new(0, 0), document_end(&document.lines), value.as_str().unwrap_or_default().to_string())];
        let edits = super::format::more_minimal_edits(&document.lines, whole).into_iter().map(|(start, end, text)| (start, end, text, false)).collect();
        drop(document);
        self.apply_model_edits(scheme, path, edits, true, cx);
        Ok(Value::Null)
    }

    /// New text for a model in one edit, after which the model is clean with `clean`: a content provider's model is
    /// no text file model, and a file read again matches the disk.
    pub(super) fn replace_model_text(&mut self, scheme: &str, path: &Path, text: String, clean: bool, cx: &mut Context<Self>) {
        let end = document_end(&self.editors.model(scheme, path).expect("the caller found the model").document().lines);
        self.apply_model_edits(scheme, path, vec![(Position::new(0, 0), end, text, false)], clean, cx);
    }

    fn apply_model_edits(&mut self, scheme: &str, path: &Path, edits: Vec<(Position, Position, String, bool)>, clean: bool, cx: &mut Context<Self>) {
        let model = self.editors.model_mut(scheme, path).expect("the caller found the model");
        let change = model.execute_edits(edits, None, EditReason::ApplyEdits);
        if clean {
            model.mark_saved();
        }
        if let Some(change) = change {
            self.model_content_changed(Some(change), crate::workbench::model_events::Cursor::model_change(), cx);
        }
    }

    /// `$trySaveDocument`: `textFileService.save`, true once the model is saved, after its dialogs; a clean model is not
    /// written. extension_host_restart.rs `serve_main_thread_requests` awaits the answer.
    pub(crate) fn try_save_document(&mut self, uri: &Value, cx: &mut Context<Self>) -> Result<futures::channel::oneshot::Receiver<bool>, Value> {
        let (scheme, ref path) = uri_parts(uri)?;
        let Some(model) = self.editors.model_mut(scheme, path) else { return Ok(saved_already(false)) };
        // textFileService.ts `save`: an untitled model saves as its associated file, or as the path the save dialog picks.
        if scheme == "untitled" && model.text_model().associated_file && (self.skip_dialogs || !path.exists()) {
            return Ok(saved_already(self.do_save_as(scheme, path, path.clone(), Default::default(), cx)));
        }
        Ok(self.save_model(scheme.to_string(), path.clone(), SaveReason::Explicit, cx))
    }

    /// First half of `$trySaveDocument` through a provider: false without a model, true when clean, else the bytes to write.
    pub(crate) fn provider_save_bytes(&mut self, uri: &Value, cx: &mut Context<Self>) -> HostResult {
        let (scheme, ref path) = uri_parts(uri)?;
        match self.editors.model(scheme, path) {
            None => return Ok(json!(false)),
            Some(model) if !model.is_dirty() => return Ok(json!(true)),
            Some(_) => self.run_save_participants(scheme, path, SaveReason::Explicit, super::text_input::SavePhase::All, cx),
        }
        Ok(json!(self.editors.model(scheme, path).expect("participants keep the model").saved_bytes()))
    }

    /// Second half: the provider wrote the bytes, so the model is clean.
    pub(crate) fn provider_saved(&mut self, uri: &Value, cx: &mut Context<Self>) -> HostResult {
        let (scheme, ref path) = uri_parts(uri)?;
        let Some(model) = self.editors.model_mut(scheme, path) else { return Ok(json!(false)) };
        model.mark_saved();
        let model = self.editors.model(scheme, path).expect("just saved");
        self.host.send_saved(&self.editors, model, true);
        cx.notify();
        Ok(json!(true))
    }

    /// `$tryShowTextDocument`: opens the model in the group, preview unless pinned, and returns the editor's id.
    pub(crate) fn try_show_text_document(&mut self, uri: &Value, options: &Value, window: &mut Window, cx: &mut Context<Self>) -> HostResult {
        // A notebook cell's document shows in its notebook's editor.
        if uri["scheme"] == crate::notebook::CELL_SCHEME
            && let Some(shown) = self.show_notebook_of_cell(uri, options, window, cx)
        {
            return shown;
        }
        let (scheme, ref path) = uri_parts(uri)?;
        self.activate_column(&options["position"], Some((scheme, path)));
        let revealed = self.reveal_group(options, |editor| editor.document().is(scheme, path));
        if let Some(group) = revealed {
            self.activate_group(group);
        } else if !super::editor_groups::explicit_group(&options["position"]) {
            self.enter_modal_group_for_all(window, cx);
        }
        if revealed.is_none() && !options["position"].as_i64().is_some_and(|column| column >= 0) {
            self.leave_locked_group(scheme, path);
        }
        let pinned = options["pinned"] == json!(true);
        if let Some(index) = self.editors.editors.iter().position(|editor| editor.document().is(scheme, path)) {
            self.editors.activate(index);
            if pinned {
                self.editors.pin(index);
            }
        } else if let Some(index) = self.editors.models.iter().position(|model| model.document().is(scheme, path)) {
            // editorGroupView.ts pins a dirty editor when it opens.
            let preview = !pinned && !self.editors.models[index].is_dirty();
            self.editors.show_model(index, preview);
        } else if on_disk(scheme) {
            let document = self.read_document(scheme, path).map_err(|error| serialized_error(&format!("Unable to read file '{}' ({error})", path.display())))?;
            self.editors.open(document, !pinned);
        } else {
            return Err(serialized_error(&format!("Unable to resolve resource {scheme}:{}", path.display())));
        }
        self.marked_text = None;
        if !options["selection"].is_null() {
            let viewport = self.editors.viewport;
            let editor = self.editors.active_mut().expect("just shown");
            let (start, end) = selection_range(editor, &options["selection"]);
            editor.move_to(start, false);
            editor.move_to(end, true);
            // editorOptions.ts applyTextEditorOptions: `TextEditorSelectionRevealType`, the center without one.
            let reveal = match options["selectionRevealType"].as_u64() {
                Some(1) => VerticalReveal::CenterIfOutsideViewport,
                Some(2) => VerticalReveal::NearTop,
                Some(3) => VerticalReveal::NearTopIfOutsideViewport,
                _ => VerticalReveal::Center,
            };
            editor.reveal_range(start, end, reveal, viewport);
        }
        if options["preserveFocus"] != json!(true) {
            window.focus(&self.editor_focus, cx);
        }
        self.editors_changed(cx);
        Ok(json!(snapshot_id(self.editors.active().expect("just shown"))))
    }

    /// editorCommands.ts `_workbench.open`: a resource in the editor group, a web link in the browser.
    /// `api_open_editor` of a resource no model holds yet and no file is: its text comes from the extension host's
    /// content or file system provider first (textFileEditorModel.ts reads through `fileService`).
    pub(super) fn api_open_editor_resolving(&mut self, args: Vec<Value>, window: &mut Window, cx: &mut Context<Self>) -> Outcome {
        let unresolved = match uri_parts(args.first().unwrap_or(&Value::Null)) {
            Ok((scheme, path)) => !matches!(scheme, "file" | "untitled" | "command") && self.editors.model(scheme, &path).is_none(),
            Err(_) => false,
        };
        if !unresolved {
            return Outcome::Ready(self.api_open_editor(&args, window, cx));
        }
        let content = self.host.call("workbench", "resolveTextContent", vec![args[0].clone()]);
        let (sender, receiver) = futures::channel::oneshot::channel();
        cx.spawn_in(window, async move |workbench, cx| {
            let content = content.await.ok().and_then(Result::ok);
            let result = workbench.update_in(cx, |workbench, window, cx| {
                if let Some(content) = content {
                    workbench.try_open_document(&args[0], &Value::Null, &content, false, cx)?;
                }
                workbench.api_open_editor(&args, window, cx)
            });
            drop(sender.send(result.unwrap_or_else(|_| Err(serialized_error("Canceled")))));
        })
        .detach();
        Outcome::Pending(receiver)
    }

    pub(super) fn api_open_editor(&mut self, args: &[Value], window: &mut Window, cx: &mut Context<Self>) -> HostResult {
        let resource = args.first().unwrap_or(&Value::Null);
        if let Some(link) = resource.as_str() {
            // extHostApiCommands.ts lets only http and https strings through; the opener service shows them in the browser.
            if !matches!(link.split(':').next(), Some("http" | "https")) {
                return Err(serialized_error(&format!("Unable to open '{link}'")));
            }
            drop(self.open_link(super::opener::Target::Text(link.to_owned()), super::opener::OpenOptions::default(), window, cx));
            return Ok(Value::Null);
        }
        let (scheme, _) = uri_parts(resource)?;
        match scheme {
            // "do not allow to execute commands from here"
            "command" => return Ok(Value::Null),
            // An untitled resource with a path opens as an untitled editor saved to that file.
            "untitled" => drop(self.try_open_document(resource, &Value::Null, &Value::Null, false, cx)?),
            _ => {}
        }
        let column_and_options = args.get(1).unwrap_or(&Value::Null);
        let mut options = column_and_options[1].clone();
        // `_workbench.open` and `_workbench.openWith` carry the column in the options already.
        if (options.is_object() || options.is_null()) && options["position"].is_null() {
            options["position"] = column_and_options[0].clone();
        }
        self.try_show_text_document(resource, &options, window, cx)?;
        Ok(Value::Null)
    }

    /// `setSelections`: one cursor per selection, the first the primary one; nothing scrolls.
    pub(crate) fn set_host_selections(&mut self, selections: &Value, cx: &mut Context<Self>) -> HostResult {
        let editor = self.editors.active_mut().expect("with_host_editor made it active");
        let selections: Vec<Selection> = selections
            .as_array()
            .into_iter()
            .flatten()
            .map(|selection| Selection {
                anchor: position(editor, &selection["selectionStartLineNumber"], &selection["selectionStartColumn"]),
                head: position(editor, &selection["positionLineNumber"], &selection["positionColumn"]),
            })
            .collect();
        if selections.is_empty() {
            return Ok(Value::Null);
        }
        editor.set_selections(selections);
        self.cursor_position_changed(Cursor { moved: true, source: "api", reveal: Reveal::Nothing }, cx);
        cx.notify();
        Ok(Value::Null)
    }

    /// mainThreadEditor.ts `revealRange`: `TextEditorRevealType` Default, InCenter, InCenterIfOutsideViewport, AtTop.
    pub(crate) fn reveal_host_range(&mut self, range_value: &Value, reveal_type: &Value, cx: &mut Context<Self>) -> HostResult {
        let reveal = match reveal_type.as_u64() {
            Some(1) => VerticalReveal::Center,
            Some(2) => VerticalReveal::CenterIfOutsideViewport,
            Some(3) => VerticalReveal::Top,
            _ => VerticalReveal::Simple,
        };
        // mainThreadEditor.ts `_revealRange` scrolls with `ScrollType.Smooth`.
        let scrolled = self.scroll_smoothly(cx, |editor, viewport| {
            let (start, end) = range(editor, range_value);
            editor.reveal_range(start, end, reveal, viewport);
        });
        if scrolled {
            self.editor_scrolled(cx);
        }
        Ok(Value::Null)
    }

    /// mainThreadEditor.ts `setConfiguration`: `_setIndentConfiguration` (tab size, indent size and spaces, or "auto" to
    /// detect them again from the text), then the code editor's `cursorStyle` and `lineNumbers`.
    pub(crate) fn set_host_options(&mut self, options: &Value, cx: &mut Context<Self>) -> HostResult {
        let editor = self.editors.active_mut().expect("with_host_editor made it active");
        if options["tabSize"] == json!("auto") || options["insertSpaces"] == json!("auto") {
            let created = creation_options(&self.settings.lock().unwrap().configuration, &editor.document().path, &editor.document().language_id);
            let insert_spaces = options["insertSpaces"].as_bool().unwrap_or(created.insert_spaces);
            let tab_size = options["tabSize"].as_u64().map_or(created.tab_size, |size| size as usize);
            editor.detect_indentation(insert_spaces, tab_size);
        } else {
            let mut indentation = editor.document().indentation;
            if let Some(insert_spaces) = options["insertSpaces"].as_bool() {
                indentation.insert_spaces = insert_spaces;
            }
            if let Some(tab_size) = options["tabSize"].as_u64() {
                indentation.tab_size = tab_size as usize;
            }
            match &options["indentSize"] {
                Value::Number(size) => indentation.indent_size = size.as_u64().map(|size| size as usize),
                Value::String(size) if size == "tabSize" => indentation.indent_size = None,
                _ => {}
            }
            editor.set_indentation(indentation);
        }
        // `cursorStyleToString`
        match options["cursorStyle"].as_u64() {
            Some(1) => editor.cursor_style_override = Some("line"),
            Some(2) => editor.cursor_style_override = Some("block"),
            Some(3) => editor.cursor_style_override = Some("underline"),
            Some(4) => editor.cursor_style_override = Some("line-thin"),
            Some(5) => editor.cursor_style_override = Some("block-outline"),
            Some(6) => editor.cursor_style_override = Some("underline-thin"),
            _ => {}
        }
        if !options["lineNumbers"].is_null() {
            editor.line_numbers_override = Some(match options["lineNumbers"].as_u64() {
                Some(1) => "on",
                Some(2) => "relative",
                Some(3) => "interval",
                _ => "off",
            });
        }
        let editor = self.editors.active().expect("with_host_editor made it active");
        let options = self.host_editor_options(editor);
        if self.host.send_options(editor, options) {
            cx.notify();
        }
        Ok(Value::Null)
    }

    /// mainThreadEditor.ts `applyEdits`: false when the model moved past the host's version.
    pub(crate) fn apply_host_edits(&mut self, version: &Value, edits: &Value, options: &Value, cx: &mut Context<Self>) -> HostResult {
        let editor = self.editors.active_mut().expect("with_host_editor made it active");
        if version.as_u64() != Some(editor.text_model().version_id.into()) {
            return Ok(json!(false));
        }
        if let Some(eol_change) = options["setEndOfLine"].as_u64().and_then(|sequence| editor.push_eol(sequence)) {
            self.model_content_changed(Some(eol_change), Cursor::model_change(), cx);
        }
        let editor = self.editors.active_mut().expect("with_host_editor made it active");
        let edits = edits
            .as_array()
            .into_iter()
            .flatten()
            .map(|edit| {
                let (start, end) = range(editor, &edit["range"]);
                (start, end, edit["text"].as_str().unwrap_or_default().to_string(), edit["forceMoveMarkers"] == json!(true))
            })
            .collect();
        if options["undoStopBefore"] == json!(true) {
            editor.push_undo_stop();
        }
        let change = editor.execute_edits(edits, None, EditReason::Unknown("MainThreadTextEditor"));
        if options["undoStopAfter"] == json!(true) {
            editor.push_undo_stop();
        }
        if change.is_some() {
            self.model_content_changed(change, Cursor { moved: true, source: "MainThreadTextEditor", reveal: Reveal::All }, cx);
        }
        Ok(json!(true))
    }

    /// mainThreadEditor.ts `insertSnippet`: the snippet replaces every range, and each copy's first tab stop is selected.
    pub(crate) fn insert_host_snippet(&mut self, version: &Value, template: &Value, ranges: &Value, options: &Value, window: &mut Window, cx: &mut Context<Self>) -> HostResult {
        let clipboard = cx.read_from_clipboard().and_then(|item| item.text());
        let editor = self.editors.active_mut().expect("with_host_editor made it active");
        if version.as_u64() != Some(editor.text_model().version_id.into()) {
            return Ok(json!(false));
        }
        window.focus(&self.editor_focus, cx);
        let mut ranges: Vec<(Position, Position)> = ranges.as_array().into_iter().flatten().map(|value| range(editor, value)).collect();
        if ranges.is_empty() {
            ranges = editor.selections.iter().map(|selection| (selection.start(), selection.end())).collect();
        }
        let template = template.as_str().unwrap_or_default();
        let keep_whitespace = options["keepWhitespace"] == json!(true);
        let snippets: Vec<_> = ranges.into_iter().map(|(start, end)| (start, end, template, keep_whitespace)).collect();
        let insert = SnippetInsert { snippets: &snippets, clipboard: clipboard.as_deref(), undo_stop_before: options["undoStopBefore"] == json!(true), undo_stop_after: options["undoStopAfter"] == json!(true), reason: "snippet" };
        self.insert_snippets(insert, cx);
        Ok(json!(true))
    }
}

/// `SnippetSession`: each template, with whitespace adjusted unless kept, replaces its range; the selections are
/// each copy's first tab stop. The expanded templates come back in the order given.
pub(super) fn snippet_edits(editor: &OpenEditor, languages: &Languages, snippets: &[(Position, Position, &str, bool)], clipboard: Option<&str>) -> (Vec<(Position, Position, String, bool)>, Vec<Selection>, Vec<SnippetText>) {
    let mut cursor_edits = Vec::new();
    let mut texts = Vec::new();
    for &(start, end, template, keep_whitespace) in snippets {
        let line_indent: String = editor.document().lines[start.line].chars().take(start.column).take_while(|c| *c == ' ' || *c == '\t').collect();
        let snippet = expand_snippet(template, &line_indent, !keep_whitespace, editor.document().indentation, |name| snippet_variable(name, editor, languages, start, end, clipboard));
        let prefix = |chars: usize| snippet.text.chars().take(chars).collect::<String>();
        let selection = Selection { anchor: end_of(start, &prefix(snippet.selection.start)), head: end_of(start, &prefix(snippet.selection.end)) };
        cursor_edits.push(CursorEdit::new(vec![Replace::new(start, end, snippet.text.clone())], selection));
        texts.push(snippet);
    }
    let before: Vec<Selection> = snippets.iter().map(|&(start, end, _, _)| Selection { anchor: start, head: end }).collect();
    let selections = selections_after(&cursor_edits, &before);
    let edits = cursor_edits.into_iter().flat_map(|edit| edit.replaces).map(|replace| (replace.start, replace.end, replace.text, false)).collect();
    (edits, selections, texts)
}

/// `Color.Format.CSS.formatHexA`: `#rrggbbaa` in lower case; the empty first entry stays empty.
fn css_hex_alpha(color: &str) -> String {
    match color.len() {
        0 => String::new(),
        7 => format!("{}ff", color.to_lowercase()),
        _ => color.to_lowercase(),
    }
}

/// snippetVariables.ts: the selection, model and file variables; the rest insert their default.
fn snippet_variable(name: &str, editor: &OpenEditor, languages: &Languages, start: Position, end: Position, clipboard: Option<&str>) -> Option<String> {
    let lines = &editor.document().lines;
    let path = &editor.document().path;
    match name {
        "CLIPBOARD" => clipboard.map(str::to_owned),
        "SELECTION" | "TM_SELECTED_TEXT" => Some(text_between(lines, start, end)).filter(|text| !text.is_empty()),
        "TM_CURRENT_LINE" => Some(lines[end.line].clone()),
        "TM_CURRENT_WORD" => editor.document().word_at(languages, end.line, end.column).map(|word| lines[end.line].chars().skip(word.start).take(word.len()).collect()),
        "TM_LINE_INDEX" => Some(end.line.to_string()),
        "TM_LINE_NUMBER" => Some((end.line + 1).to_string()),
        "TM_FILENAME" => Some(editor.document().name()),
        "TM_FILENAME_BASE" => path.file_stem().map(|stem| stem.to_string_lossy().into_owned()),
        "TM_DIRECTORY" => path.parent().map(|parent| parent.to_string_lossy().into_owned()),
        "TM_FILEPATH" => Some(path.to_string_lossy().into_owned()),
        _ => None,
    }
}

fn saved_already(saved: bool) -> futures::channel::oneshot::Receiver<bool> {
    let (sender, receiver) = futures::channel::oneshot::channel();
    _ = sender.send(saved);
    receiver
}

/// The scheme and path a model is keyed by; the authority of a non-file URI leads its path as `//authority`,
/// which `TextDocument::uri` splits off again.
pub(crate) fn uri_parts(uri: &Value) -> Result<(&str, PathBuf), Value> {
    let part = |key: &str| uri[key].as_str().unwrap_or_default();
    let (scheme, authority, path, query) = (part("scheme"), part("authority"), part("path"), part("query"));
    // editor.rs `split_query`: a non-file query stays in the model's path.
    let mut query = if query.is_empty() || scheme == "file" { String::new() } else { format!("?{query}") };
    // editor.rs `split_fragment`: a notebook cell's or playground snippet's fragment too.
    if crate::editor::has_fragment(scheme) {
        query.push('#');
        query.push_str(part("fragment"));
    }
    match (scheme, authority) {
        ("", _) => Err(serialized_error("Invalid uri. Scheme and authority or path must be set.")),
        ("file", _) | (_, "") if path.is_empty() => Err(serialized_error("Invalid uri. Scheme and authority or path must be set.")),
        ("file", _) if cfg!(windows) => Ok((scheme, PathBuf::from(crate::uri::fs_path(scheme, authority, path)))),
        ("file", _) | (_, "") => Ok((scheme, PathBuf::from(format!("{path}{query}")))),
        _ => Ok((scheme, PathBuf::from(format!("//{authority}{path}{query}")))),
    }
}

/// `IRange`, 1-based with UTF-16 columns, validated against the model as `validateRange` does.
pub(super) fn range(editor: &OpenEditor, range: &Value) -> (Position, Position) {
    let start = position(editor, &range["startLineNumber"], &range["startColumn"]);
    let end = position(editor, &range["endLineNumber"], &range["endColumn"]);
    if end < start { (end, start) } else { (start, end) }
}

/// editorOptions.ts `applyTextEditorOptions`: a selection without its end is the caret at its start.
pub(super) fn selection_range(editor: &OpenEditor, selection: &Value) -> (Position, Position) {
    let start = position(editor, &selection["startLineNumber"], &selection["startColumn"]);
    let end_line = selection.get("endLineNumber").filter(|line| !line.is_null()).unwrap_or(&selection["startLineNumber"]);
    let end_column = selection.get("endColumn").filter(|column| !column.is_null()).unwrap_or(&selection["startColumn"]);
    let end = position(editor, end_line, end_column);
    if end < start { (end, start) } else { (start, end) }
}

/// `validatePosition`: before the first line is its start, after the last line is its end.
fn position(editor: &OpenEditor, line: &Value, column: &Value) -> Position {
    let lines = &editor.document().lines;
    let line_number = line.as_f64().unwrap_or(1.);
    if line_number < 1. {
        return Position::new(0, 0);
    }
    if line_number > lines.len() as f64 {
        let last = lines.len() - 1;
        return Position::new(last, lines[last].chars().count());
    }
    let line = line_number as usize - 1;
    let column = (column.as_f64().unwrap_or(1.) as usize).saturating_sub(1);
    Position::new(line, char_column(&lines[line], column))
}