Skip to content

Visual Studio Code, rebuilt in Rust

Rust
40.4 KB
Raw Blame
//! The notebook model of contrib/notebook/common/model/notebookTextModel.ts with notebookCommon.ts: cells with their
//! outputs and metadata, the edits on them and the raw events mainThreadNotebookDocuments.ts sends the extension
//! host. A cell's text is a workbench text model at the cell's `vscode-notebook-cell` URI, so it is not kept here.

pub mod kernels;
pub mod layout;
pub mod outline;
pub mod renderers;

use base64::Engine;
use base64::engine::general_purpose::{STANDARD, URL_SAFE};
use std::collections::HashMap;

use serde::Deserialize;
use serde_json::{Map, Value, json};

use crate::editor::uri_value;

pub const CELL_SCHEME: &str = "vscode-notebook-cell";
/// The scheme of a notebook editor's tab in an editor group; its path is the notebook's URI string.
pub const NOTEBOOK_EDITOR_SCHEME: &str = "vscode-notebook-editor";

/// notebookServiceImpl.ts and the notebook parts of mainThreadNotebookDocumentsAndEditors.ts.
#[derive(Default)]
pub struct Notebooks {
    pub models: Vec<NotebookModel>,
    pub serializers: Vec<Serializer>,
    pub kernels: kernels::Kernels,
    /// One per notebook editor tab, by the tab's model id.
    pub editors: Vec<NotebookEditor>,
    /// Notebooks the extension host opened (`BoundModelReferenceCollection`): kept while no editor shows them.
    pub held: Vec<String>,
    /// What the extension host has: notebook URI strings, editor ids, the active editor, the visible ones.
    pub sent_documents: Vec<(String, Value)>,
    pub sent_editors: Vec<String>,
    pub sent_active: Option<String>,
    pub sent_visible: Vec<String>,
    /// The interactive windows (InteractiveEditorInput) and REPL editors (ReplEditorInput): notebook URI string,
    /// input URI and history.
    pub interactives: Vec<Interactive>,
    /// `mostRecentReplEditor`: the notebook URI string of the REPL editor that last got a cell.
    pub most_recent_repl: Option<String>,
    /// `interactiveWindowOpen`: an interactive window or REPL editor opened once (never reset, as upstream).
    pub interactive_window_open: bool,
    /// Renderer messages from the webviews (editor id, message) that wait for `onRenderer:<id>`, by renderer id.
    pub renderer_messages: std::collections::HashMap<String, Vec<(String, Value)>>,
}

/// An interactive window's or REPL editor's input editor model and its history (interactiveHistoryService.ts).
pub struct Interactive {
    pub notebook: String,
    pub input: Value,
    /// The window's title (`InteractiveEditorInput.windowNames`), its notebook's base name without one.
    pub title: Option<String>,
    pub history: History,
    /// A tab showed it: once none does, the window goes.
    pub shown: bool,
    /// A REPL editor (`repl` view type): its input is the notebook's last cell, the list shows the others.
    pub repl: bool,
}

/// base/common/history.ts `HistoryNavigator2` with capacity 50: distinct values, oldest first, the last one the
/// input being typed, and a cursor.
#[derive(Debug)]
pub struct History {
    entries: Vec<String>,
    cursor: usize,
}

impl History {
    const CAPACITY: usize = 50;

    pub fn new(value: &str) -> Self {
        History { entries: vec![value.to_owned()], cursor: 0 }
    }

    pub fn current(&self) -> &str {
        &self.entries[self.cursor]
    }

    /// `add`: appended (an equal older entry goes), the cursor on it, the oldest dropped past the capacity.
    pub fn add(&mut self, value: &str) {
        self.entries.retain(|entry| entry != value);
        self.entries.push(value.to_owned());
        if self.entries.len() > Self::CAPACITY {
            self.entries.remove(0);
        }
        self.cursor = self.entries.len() - 1;
    }

    /// `replaceLast`: the last entry becomes `value`, an equal older entry goes.
    pub fn replace_last(&mut self, value: &str) {
        let last = self.entries.len() - 1;
        if self.entries[last] == value {
            return;
        }
        self.entries[last] = value.to_owned();
        let mut index = 0;
        while index < self.entries.len() - 1 {
            if self.entries[index] != value {
                index += 1;
                continue;
            }
            self.entries.remove(index);
            if index < self.cursor {
                self.cursor -= 1;
            }
        }
    }

    pub fn previous(&mut self) -> &str {
        self.cursor = self.cursor.saturating_sub(1);
        self.current()
    }

    pub fn next(&mut self) -> &str {
        self.cursor = (self.cursor + 1).min(self.entries.len() - 1);
        self.current()
    }

    pub fn reset_cursor(&mut self) {
        self.cursor = self.entries.len() - 1;
    }
}

/// A `$registerNotebookSerializer`.
pub struct Serializer {
    pub handle: u64,
    pub view_type: String,
    /// `TransientOptions`.
    pub options: Value,
    /// `INotebookContributionData`: `displayName`, `filenamePattern`, `providerDisplayName`.
    pub registration: Value,
}

/// A notebook editor (notebookEditorWidget.ts) of one tab.
pub struct NotebookEditor {
    pub tab_model_id: u32,
    pub id: String,
    pub notebook: String,
    /// The focused cell's index.
    pub focus: usize,
    /// `ICellRange`s.
    pub selections: Vec<(usize, usize)>,
    /// An interactive window's input editor has the focus (not a cell).
    pub input_focused: bool,
    /// The visible cell ranges the host last heard of, None before the first frame.
    pub visible_ranges: Option<Vec<(usize, usize)>>,
    pub cell_list: CellList,
}

/// The rows notebookCellList.ts renders and the code editors they hold: the cells (handle, code) in the render range,
/// each code cell template (rowCache.ts) with the cell whose model its editor last got, and the released templates.
#[derive(Default)]
pub struct CellList {
    rendered: Vec<(u64, bool)>,
    row_templates: HashMap<u64, usize>,
    templates: Vec<u64>,
    released: Vec<usize>,
    editing_markup: Vec<u64>,
}

impl CellList {
    /// listView.ts `render` for the rows (handle, code cell, markup in edit mode) now in the render range: rows that
    /// left it release their template first, then the new rows take one, the last row first; a code cell's editor
    /// gets its model (codeCell.ts `setModel`), a released template's editor keeps it. Whether an editor's model
    /// changed.
    pub fn render(&mut self, rows: &[(u64, bool, bool)]) -> bool {
        let before = (self.templates.clone(), self.editing_markup.clone());
        let range: Vec<(u64, bool)> = rows.iter().map(|&(handle, code, _)| (handle, code)).collect();
        for row in self.rendered.iter().filter(|row| !range.contains(row)) {
            if let Some(template) = self.row_templates.remove(&row.0).filter(|_| row.1) {
                self.released.push(template);
            }
        }
        for &(handle, _) in range.iter().rev().filter(|row| row.1 && !self.rendered.contains(row)) {
            let template = self.released.pop().unwrap_or_else(|| {
                self.templates.push(handle);
                self.templates.len() - 1
            });
            self.templates[template] = handle;
            self.row_templates.insert(handle, template);
        }
        self.rendered = range;
        // markupCell.ts: a markup cell's editor lives while its row renders in edit mode.
        self.editing_markup = rows.iter().filter(|&&(_, code, editing)| !code && editing).map(|&(handle, _, _)| handle).collect();
        before != (self.templates.clone(), self.editing_markup.clone())
    }

    /// Whether the cell's code editor holds its model.
    pub fn has_editor(&self, handle: u64) -> bool {
        self.templates.contains(&handle) || self.editing_markup.contains(&handle)
    }
}

impl Notebooks {
    pub fn model(&self, uri: &str) -> Option<&NotebookModel> {
        self.models.iter().find(|model| model.uri_string() == uri)
    }

    pub fn model_mut(&mut self, uri: &str) -> Option<&mut NotebookModel> {
        self.models.iter_mut().find(|model| model.uri_string() == uri)
    }

    /// The notebook and index of a cell's text model.
    pub fn cell(&self, cell_uri: &Value) -> Option<(&NotebookModel, usize)> {
        let (notebook, _) = parse_cell_uri(cell_uri)?;
        let model = self.model(&uri_string(&notebook))?;
        Some((model, model.index_of_cell(cell_uri)?))
    }

    pub fn serializer(&self, view_type: &str) -> Option<&Serializer> {
        self.serializers.iter().find(|serializer| serializer.view_type == view_type)
    }

    pub fn editor(&self, tab_model_id: u32) -> Option<&NotebookEditor> {
        self.editors.iter().find(|editor| editor.tab_model_id == tab_model_id)
    }
}

/// `CellKind.Markup`.
pub const MARKUP: u64 = 1;
/// `CellKind.Code`.
pub const CODE: u64 = 2;

/// `NotebookCellsChangeType`.
mod change {
    pub const MODEL_CHANGE: u64 = 1;
    pub const MOVE: u64 = 2;
    pub const CELL_LANGUAGE: u64 = 5;
    pub const CELL_METADATA: u64 = 7;
    pub const OUTPUT: u64 = 8;
    pub const OUTPUT_ITEM: u64 = 9;
    pub const CELL_CONTENT: u64 = 10;
    pub const CELL_INTERNAL_METADATA: u64 = 12;
}

/// `CellEditType`.
mod edit {
    pub const REPLACE: u64 = 1;
    pub const OUTPUT: u64 = 2;
    pub const METADATA: u64 = 3;
    pub const CELL_LANGUAGE: u64 = 4;
    pub const DOCUMENT_METADATA: u64 = 5;
    pub const MOVE: u64 = 6;
    pub const OUTPUT_ITEMS: u64 = 7;
    pub const PARTIAL_METADATA: u64 = 8;
    pub const PARTIAL_INTERNAL_METADATA: u64 = 9;
}

#[derive(Clone, Debug, PartialEq, Deserialize)]
pub struct OutputItem {
    pub mime: String,
    #[serde(rename = "valueBytes", alias = "data", deserialize_with = "bytes")]
    pub data: Vec<u8>,
}

#[derive(Clone, Debug, PartialEq, Deserialize)]
pub struct Output {
    #[serde(rename = "outputId")]
    pub id: String,
    #[serde(default)]
    pub metadata: Value,
    #[serde(alias = "outputs")]
    pub items: Vec<OutputItem>,
}

/// A buffer the workbench received as bytes, or wrote itself as `{"$vsbuffer": base64}`.
fn bytes<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Vec<u8>, D::Error> {
    let value = Value::deserialize(deserializer)?;
    match &value[exthost::rpc::VSBUFFER_KEY] {
        Value::String(encoded) => STANDARD.decode(encoded).map_err(serde::de::Error::custom),
        _ => serde_json::from_value(value).map_err(serde::de::Error::custom),
    }
}

impl Output {
    /// `NotebookDto.toNotebookOutputDto`, its bytes as buffers.
    pub fn dto(&self) -> Value {
        json!({ "outputId": self.id, "metadata": self.metadata, "items": self.items.iter().map(OutputItem::dto).collect::<Vec<_>>() })
    }
}

impl OutputItem {
    pub fn dto(&self) -> Value {
        json!({ "mime": self.mime, "valueBytes": { exthost::rpc::VSBUFFER_KEY: STANDARD.encode(&self.data) } })
    }
}

#[derive(Clone, Debug)]
pub struct Cell {
    pub handle: u64,
    pub uri: Value,
    pub kind: u64,
    pub language: String,
    pub mime: Option<String>,
    pub metadata: Value,
    pub internal_metadata: Value,
    pub outputs: Vec<Output>,
}

/// A cell an edit created: the workbench makes its text model from `source`.
#[derive(Debug, PartialEq)]
pub struct NewCellText {
    pub uri: Value,
    pub source: String,
    pub language: String,
}

/// What `apply_edits` changed, for the workbench and the extension host.
#[derive(Debug, Default)]
pub struct Applied {
    /// The `$acceptModelChanged` event, `None` when nothing changed.
    pub event: Option<Value>,
    pub document_metadata_changed: bool,
    pub added: Vec<NewCellText>,
    pub removed: Vec<Cell>,
    /// `computeUndoRedo`: the edits that undo these, the last applied first. A replace's inverse names the cells it
    /// brings back in `restore` (their URIs) for the caller, which has their text, to fill in `cells`.
    pub undo: Vec<Value>,
}

pub struct NotebookModel {
    pub uri: Value,
    pub view_type: String,
    pub metadata: Value,
    pub cells: Vec<Cell>,
    pub version_id: u64,
    next_handle: u64,
    pub dirty: bool,
    /// notebookEditorModelResolverServiceImpl.ts `isScratchpad`: changes never make it dirty (an interactive window
    /// without `interactiveWindow.promptToSaveOnClose`).
    pub scratchpad: bool,
    /// Resolved by a REPL editor (repl.contribution.ts): its working copy and backups are `notebook/<type>/repl`.
    pub repl_working_copy: bool,
    /// Changed since it was created (`isModified`): a scratchpad is never dirty but still backs up when modified.
    pub modified: bool,
    /// The serializer's `TransientOptions`: `transientOutputs`, `transientCellMetadata`, `transientDocumentMetadata`.
    pub transient: Value,
}

impl NotebookModel {
    /// `NotebookTextModel` from `NotebookData` (a `NotebookDataDto`); the new cells' texts are returned with it.
    pub fn new(uri: Value, view_type: &str, data: &Value, transient: Value) -> (Self, Vec<NewCellText>) {
        let mut model = NotebookModel { uri, view_type: view_type.to_owned(), metadata: object_or_empty(&data["metadata"]), cells: Vec::new(), version_id: 0, next_handle: 0, dirty: false, scratchpad: false, repl_working_copy: false, modified: false, transient };
        let cells = data["cells"].as_array().cloned().unwrap_or_default();
        let (cells, texts) = model.create_cells(&cells);
        model.cells = cells;
        (model, texts)
    }

    pub fn uri_string(&self) -> String {
        uri_string(&self.uri)
    }

    pub fn index_of_cell(&self, cell_uri: &Value) -> Option<usize> {
        self.cells.iter().position(|cell| cell.uri["fragment"] == cell_uri["fragment"])
    }

    pub fn index_of_handle(&self, handle: u64) -> Option<usize> {
        self.cells.iter().position(|cell| cell.handle == handle)
    }

    /// `ExtHostNotebook` `INotebookModelAddedData`; `text` reads a cell's text model.
    pub fn added_data(&self, text: impl Fn(&Cell) -> String) -> Value {
        json!({
            "uri": self.uri,
            "versionId": self.version_id,
            "cells": self.cells.iter().map(|cell| cell_dto(cell, &text(cell))).collect::<Vec<_>>(),
            "viewType": self.view_type,
            "metadata": self.metadata,
        })
    }

    /// `createSnapshot` as a `NotebookDataDto` without the serializer's transient parts.
    pub fn snapshot(&self, text: impl Fn(&Cell) -> String) -> Value {
        let transient_outputs = self.transient["transientOutputs"] == true;
        let cells: Vec<Value> = self
            .cells
            .iter()
            .map(|cell| {
                json!({
                    "source": text(cell),
                    "language": cell.language,
                    "mime": cell.mime,
                    "cellKind": cell.kind,
                    "outputs": if transient_outputs { Vec::new() } else { cell.outputs.iter().map(Output::dto).collect() },
                    "metadata": without_keys(&cell.metadata, &self.transient["transientCellMetadata"]),
                    "internalMetadata": cell.internal_metadata,
                })
            })
            .collect();
        let mut metadata = without_keys(&self.metadata, &self.transient["transientDocumentMetadata"]);
        // notebookServiceImpl.ts keeps it for the ipynb serializer to write the file's indentation back.
        if let Some(indent) = self.metadata["indentAmount"].as_str().filter(|indent| !indent.is_empty()) {
            metadata["indentAmount"] = json!(indent);
        }
        json!({ "metadata": metadata, "cells": cells })
    }

    /// The bytes of every output item: `createSnapshot` refuses a backup past `notebook.backup.sizeLimit`.
    pub fn output_size(&self) -> usize {
        self.cells.iter().flat_map(|cell| &cell.outputs).flat_map(|output| &output.items).map(|item| item.data.len()).sum()
    }

    /// `applyEdits` (`ICellEditOperation`s, as `ICellEditOperationDto`s): applied from the last index to the first, as
    /// `_doApplyEdits` orders them; one event carries every change and the next version id.
    pub fn apply_edits(&mut self, edits: &[Value]) -> Result<Applied, String> {
        let mut ordered = Vec::new();
        for (original, edit) in edits.iter().enumerate() {
            let kind = edit["editType"].as_u64().unwrap_or_default();
            let index = if let Some(index) = edit["index"].as_u64() {
                Some(index as usize)
            } else if let Some(handle) = edit["handle"].as_u64() {
                Some(self.index_of_handle(handle).ok_or_else(|| format!("model cannot find cell with handle {handle}"))?)
            } else if let Some(output_id) = edit["outputId"].as_str() {
                // An output cleared by an earlier edit is no error: the edit is dropped.
                match self.cells.iter().position(|cell| cell.outputs.iter().any(|output| output.id == output_id)) {
                    Some(index) => Some(index),
                    None => continue,
                }
            } else if kind == edit::DOCUMENT_METADATA {
                None
            } else {
                return Err(format!("Invalid cell edit: {edit}"));
            };
            let end = match kind {
                edit::DOCUMENT_METADATA => None,
                edit::REPLACE => Some(index.unwrap_or_default() + edit["count"].as_u64().unwrap_or_default() as usize),
                _ => index,
            };
            ordered.push((edit, index, end, original));
        }
        ordered.sort_by(|a, b| match (a.2, b.2) {
            (None, None) => std::cmp::Ordering::Equal,
            (None, _) => std::cmp::Ordering::Less,
            (_, None) => std::cmp::Ordering::Greater,
            (Some(a_end), Some(b_end)) => b_end.cmp(&a_end).then(b.3.cmp(&a.3)),
        });
        // Edits on one index: the others in reverse, then the replaces.
        let mut runs: Vec<Vec<(&Value, Option<usize>)>> = Vec::new();
        for (edit, index, _, _) in ordered {
            match runs.last_mut().filter(|run| run[0].1 == index) {
                Some(run) => run.push((edit, index)),
                None => runs.push(vec![(edit, index)]),
            }
        }
        let mut applied = Applied::default();
        let mut events = Vec::new();
        let mut dirtying = false;
        for run in runs {
            let (replaces, mut others): (Vec<_>, Vec<_>) = run.into_iter().partition(|(edit, _)| edit["editType"] == edit::REPLACE);
            others.reverse();
            for (edit, index) in others.into_iter().chain(replaces) {
                dirtying |= self.apply_edit(edit, index, &mut events, &mut applied)?;
            }
        }
        if events.is_empty() && !applied.document_metadata_changed {
            return Ok(applied);
        }
        self.version_id += 1;
        self.dirty |= dirtying && !self.scratchpad;
        self.modified |= dirtying;
        applied.event = Some(json!({ "rawEvents": events, "versionId": self.version_id }));
        Ok(applied)
    }

    /// One edit; whether it makes the notebook dirty (a change the serializer keeps).
    fn apply_edit(&mut self, edit: &Value, index: Option<usize>, events: &mut Vec<Value>, applied: &mut Applied) -> Result<bool, String> {
        let kind = edit["editType"].as_u64().unwrap_or_default();
        let cell_index = |model: &Self| index.filter(|index| *index < model.cells.len()).ok_or_else(|| format!("model index out of range {index:?}"));
        match kind {
            edit::REPLACE => {
                let index = index.unwrap_or_default().min(self.cells.len());
                let count = (edit["count"].as_u64().unwrap_or_default() as usize).min(self.cells.len() - index);
                let dtos = edit["cells"].as_array().cloned().unwrap_or_default();
                if count == 0 && dtos.is_empty() {
                    return Ok(false);
                }
                let (cells, texts) = self.create_cells(&dtos);
                let dtos: Vec<Value> = cells.iter().zip(&texts).map(|(cell, text)| cell_dto(cell, &text.source)).collect();
                let added = cells.len();
                let removed: Vec<Cell> = self.cells.splice(index..index + count, cells).collect();
                let restore: Vec<Value> = removed.iter().map(|cell| cell.uri.clone()).collect();
                applied.undo.insert(0, json!({ "editType": edit::REPLACE, "index": index, "count": added, "cells": [], "restore": restore }));
                applied.removed.extend(removed);
                applied.added.extend(texts);
                events.push(json!({ "kind": change::MODEL_CHANGE, "changes": [[index, count, dtos]] }));
                Ok(true)
            }
            edit::MOVE => {
                let (index, length, new_index) = (index.unwrap_or_default(), edit["length"].as_u64().unwrap_or_default() as usize, edit["newIdx"].as_u64().unwrap_or_default() as usize);
                if index + length > self.cells.len() || new_index + length > self.cells.len() {
                    return Err(format!("model index out of range {index}"));
                }
                let moved: Vec<Cell> = self.cells.drain(index..index + length).collect();
                self.cells.splice(new_index..new_index, moved);
                applied.undo.insert(0, json!({ "editType": edit::MOVE, "index": new_index, "length": length, "newIdx": index }));
                events.push(json!({ "kind": change::MOVE, "index": index, "length": length, "newIdx": new_index }));
                Ok(true)
            }
            edit::OUTPUT => {
                let index = cell_index(self)?;
                let outputs: Vec<Output> = serde_json::from_value(edit["outputs"].clone()).map_err(|error| error.to_string())?;
                let cell = &mut self.cells[index];
                if edit["append"] == true {
                    cell.outputs.extend(outputs);
                } else if cell.outputs == outputs {
                    return Ok(false);
                } else {
                    cell.outputs = outputs;
                }
                events.push(json!({ "kind": change::OUTPUT, "index": index, "outputs": cell.outputs.iter().map(Output::dto).collect::<Vec<_>>() }));
                Ok(self.transient["transientOutputs"] != true)
            }
            edit::OUTPUT_ITEMS => {
                let index = cell_index(self)?;
                let output_id = edit["outputId"].as_str().unwrap_or_default();
                let items: Vec<OutputItem> = serde_json::from_value(edit["items"].clone()).map_err(|error| error.to_string())?;
                let append = edit["append"] == true;
                let output = self.cells[index].outputs.iter_mut().find(|output| output.id == output_id).expect("found by its id");
                match append {
                    true => output.items.extend(items.iter().cloned()),
                    false => output.items = items.clone(),
                }
                merge_streams(&mut output.items);
                events.push(json!({ "kind": change::OUTPUT_ITEM, "index": index, "outputId": output_id, "outputItems": items.iter().map(OutputItem::dto).collect::<Vec<_>>(), "append": append }));
                Ok(self.transient["transientOutputs"] != true)
            }
            edit::METADATA | edit::PARTIAL_METADATA => {
                let index = cell_index(self)?;
                let old = self.cells[index].metadata.clone();
                let metadata = match kind {
                    edit::METADATA => object_or_empty(&edit["metadata"]),
                    _ => merged(&old, &edit["metadata"]),
                };
                if metadata == old {
                    return Ok(false);
                }
                self.cells[index].metadata = metadata.clone();
                applied.undo.insert(0, json!({ "editType": edit::METADATA, "index": index, "metadata": old }));
                events.push(json!({ "kind": change::CELL_METADATA, "index": index, "metadata": metadata }));
                let transient = &self.transient["transientCellMetadata"];
                Ok(without_keys(&old, transient) != without_keys(&metadata, transient))
            }
            edit::PARTIAL_INTERNAL_METADATA => {
                let index = cell_index(self)?;
                let internal_metadata = merged(&self.cells[index].internal_metadata, &edit["internalMetadata"]);
                self.cells[index].internal_metadata = internal_metadata.clone();
                events.push(json!({ "kind": change::CELL_INTERNAL_METADATA, "index": index, "internalMetadata": internal_metadata }));
                Ok(false)
            }
            edit::CELL_LANGUAGE => {
                let index = cell_index(self)?;
                let language = edit["language"].as_str().unwrap_or_default().to_owned();
                if self.cells[index].language == language {
                    return Ok(false);
                }
                let old = std::mem::replace(&mut self.cells[index].language, language.clone());
                applied.undo.insert(0, json!({ "editType": edit::CELL_LANGUAGE, "index": index, "language": old }));
                events.push(json!({ "kind": change::CELL_LANGUAGE, "index": index, "language": language }));
                Ok(true)
            }
            edit::DOCUMENT_METADATA => {
                let metadata = object_or_empty(&edit["metadata"]);
                if metadata == self.metadata {
                    return Ok(false);
                }
                let transient = &self.transient["transientDocumentMetadata"];
                let dirtying = without_keys(&self.metadata, transient) != without_keys(&metadata, transient);
                let old = std::mem::replace(&mut self.metadata, metadata);
                applied.undo.insert(0, json!({ "editType": edit::DOCUMENT_METADATA, "metadata": old }));
                applied.document_metadata_changed = true;
                Ok(dirtying)
            }
            _ => Err(format!("Invalid cell edit: {edit}")),
        }
    }

    /// `_bindCellContentHandler` for a text change of the cell at `index`: the next version, dirty.
    pub fn cell_content_changed(&mut self, index: usize) -> Value {
        self.version_id += 1;
        self.dirty |= !self.scratchpad;
        self.modified = true;
        json!({ "rawEvents": [{ "kind": change::CELL_CONTENT, "index": index }], "versionId": self.version_id })
    }

    /// `ICellDto2`s as new cells with the next handles.
    fn create_cells(&mut self, dtos: &[Value]) -> (Vec<Cell>, Vec<NewCellText>) {
        let mut cells = Vec::new();
        let mut texts = Vec::new();
        for dto in dtos {
            let handle = self.next_handle;
            self.next_handle += 1;
            let uri = cell_uri(&self.uri, handle);
            let language = dto["language"].as_str().unwrap_or_default().to_owned();
            let outputs = serde_json::from_value(dto["outputs"].clone()).unwrap_or_default();
            texts.push(NewCellText { uri: uri.clone(), source: dto["source"].as_str().unwrap_or_default().to_owned(), language: language.clone() });
            cells.push(Cell {
                handle,
                uri,
                kind: dto["cellKind"].as_u64().unwrap_or(CODE),
                language,
                mime: dto["mime"].as_str().map(str::to_owned),
                metadata: object_or_empty(&dto["metadata"]),
                internal_metadata: object_or_empty(&dto["internalMetadata"]),
                outputs,
            });
        }
        (cells, texts)
    }
}

/// `NotebookDto.toNotebookCellDto`.
fn cell_dto(cell: &Cell, text: &str) -> Value {
    let lines: Vec<&str> = text.split('\n').map(|line| line.strip_suffix('\r').unwrap_or(line)).collect();
    let eol = if text.contains("\r\n") { "\r\n" } else { "\n" };
    json!({
        "handle": cell.handle,
        "uri": cell.uri,
        "eol": eol,
        "source": lines,
        "language": cell.language,
        "mime": cell.mime,
        "cellKind": cell.kind,
        "outputs": cell.outputs.iter().map(Output::dto).collect::<Vec<_>>(),
        "metadata": cell.metadata,
        "internalMetadata": cell.internal_metadata,
    })
}

/// notebookDocumentService.ts `generate`: the notebook's URI with the cell scheme and a fragment of the handle in
/// base 7 (its length as a letter first) and the notebook's scheme in URL-safe base64.
pub fn cell_uri(notebook: &Value, handle: u64) -> Value {
    const LENGTHS: [char; 10] = ['W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f'];
    let mut digits = Vec::new();
    let mut rest = handle;
    loop {
        digits.push(char::from_digit((rest % 7) as u32, 7).expect("a base 7 digit"));
        rest /= 7;
        if rest == 0 {
            break;
        }
    }
    let radix7: String = digits.into_iter().rev().collect();
    let prefix = LENGTHS.get(radix7.len() - 1).copied().unwrap_or('z');
    let scheme = URL_SAFE.encode(notebook["scheme"].as_str().unwrap_or_default());
    with_scheme_and_fragment(notebook, CELL_SCHEME, &format!("{prefix}{radix7}s{scheme}"))
}

/// `uri.with({ scheme, fragment })` of `UriComponents`; a revived URI's cached `external` and `fsPath` would
/// otherwise still name the old one.
fn with_scheme_and_fragment(uri: &Value, scheme: &str, fragment: &str) -> Value {
    json!({ "$mid": 1, "scheme": scheme, "authority": uri["authority"], "path": uri["path"], "query": uri["query"], "fragment": fragment })
}

/// notebookDocumentService.ts `parse`: the notebook URI and handle of a cell URI.
pub fn parse_cell_uri(cell: &Value) -> Option<(Value, u64)> {
    if cell["scheme"] != CELL_SCHEME {
        return None;
    }
    let fragment = cell["fragment"].as_str()?;
    let (handle, scheme) = fragment.split_once('s')?;
    let handle = u64::from_str_radix(handle.trim_start_matches(|c: char| ('W'..='Z').contains(&c) || ('a'..='f').contains(&c)), 7).ok()?;
    let scheme = String::from_utf8(URL_SAFE.decode(scheme).ok()?).ok()?;
    Some((with_scheme_and_fragment(cell, &scheme, ""), handle))
}

/// `URI.toString()` of `UriComponents`, enough to compare notebooks.
pub fn uri_string(uri: &Value) -> String {
    let part = |key: &str| uri[key].as_str().unwrap_or_default();
    let path = match part("authority") {
        "" => part("path").to_owned(),
        authority => format!("//{authority}{}", part("path")),
    };
    let mut text = crate::editor::uri_string(part("scheme"), std::path::Path::new(&path));
    if !part("query").is_empty() {
        text.push('?');
        text.push_str(part("query"));
    }
    if !part("fragment").is_empty() {
        text.push('#');
        text.push_str(part("fragment"));
    }
    text
}

/// `NotebookWorkingCopyTypeIdentifier.create` with the view type as the notebook type: a notebook's backup type id.
pub fn working_copy_type_id(view_type: &str) -> String {
    format!("notebook/{view_type}/{view_type}")
}

/// The backup type id of a notebook shown as a REPL editor (ReplEditorInput resolves it with view type `repl`).
pub fn repl_working_copy_type_id(notebook_type: &str) -> String {
    format!("notebook/{notebook_type}/repl")
}

/// ReplWindowWorkingCopyEditorHandler `handles`: the notebook type of a REPL editor's backup type id.
pub fn repl_notebook_type_of_working_copy(type_id: &str) -> Option<&str> {
    let (notebook_type, view_type) = type_id.strip_prefix("notebook/")?.split_once('/')?;
    (view_type == "repl" && !notebook_type.is_empty()).then_some(notebook_type)
}

/// SimpleNotebookWorkingCopyEditorHandler `_getViewType`: the view type of a notebook backup's type id, `None` for
/// other type ids, a notebook type differing from its view type, and the interactive window.
pub fn view_type_of_working_copy(type_id: &str) -> Option<&str> {
    let (notebook_type, view_type) = type_id.strip_prefix("notebook/")?.split_once('/')?;
    (notebook_type == view_type && !view_type.contains('/') && view_type != "interactive").then_some(view_type)
}

/// InteractiveEditorInput `name`: the window's title, else its notebook's base name without the extension.
pub fn interactive_name(uri: &Value, interactive: &Interactive) -> String {
    if let Some(title) = &interactive.title {
        return title.clone();
    }
    let name = label(uri);
    name.rsplit_once('.').map_or(name.clone(), |(stem, _)| stem.to_owned())
}

/// The tab label of a notebook: its resource's base name (`EditorInput.getName`).
pub fn label(uri: &Value) -> String {
    let path = uri["path"].as_str().unwrap_or_default();
    path.rsplit('/').next().unwrap_or(path).to_owned()
}

/// `URI.from({ scheme: untitled, path: Untitled-N<ending>, query: viewType })` for `createUntitledUri`.
pub fn untitled_uri(counter: usize, ending: &str, view_type: &str) -> Value {
    let mut uri = uri_value("untitled", std::path::Path::new(&format!("Untitled-{counter}{ending}")));
    uri["query"] = json!(view_type);
    uri
}

/// notebookCellOutputTextModel.ts `optimizeOutputItems`: an output of stream items only keeps one item per mime,
/// their bytes in order through `compressOutputItemStreams`.
fn merge_streams(items: &mut Vec<OutputItem>) {
    let is_stream = |item: &OutputItem| matches!(item.mime.as_str(), "application/vnd.code.notebook.stdout" | "application/vnd.code.notebook.stderr");
    if items.len() < 2 || !items.iter().all(is_stream) {
        return;
    }
    let mut streams: Vec<(OutputItem, Vec<Vec<u8>>)> = Vec::new();
    for item in items.drain(..) {
        match streams.iter_mut().find(|(first, _)| first.mime == item.mime) {
            Some((_, buffers)) => buffers.push(item.data),
            None => streams.push((OutputItem { data: Vec::new(), ..item.clone() }, vec![item.data])),
        }
    }
    for (mut item, buffers) in streams {
        item.data = compress_output_item_streams(buffers);
        items.push(item);
    }
}

const MOVE_CURSOR_1_LINE_COMMAND: &[u8] = b"\x1b[A";

/// notebookCommon.ts `compressOutputItemStreams`: a stream that starts by moving the cursor up a line drops the
/// previous stream's last line, then backspaces and carriage returns rewrite the text.
pub fn compress_output_item_streams(mut buffers: Vec<Vec<u8>>) -> Vec<u8> {
    for index in 1..buffers.len() {
        if !buffers[index].starts_with(MOVE_CURSOR_1_LINE_COMMAND) {
            continue;
        }
        let Some(last_line_feed) = buffers[index - 1].iter().rposition(|byte| *byte == b'\n') else { continue };
        buffers[index - 1].truncate(last_line_feed);
        buffers[index].drain(..MOVE_CURSOR_1_LINE_COMMAND.len());
    }
    format_stream_text(buffers.concat())
}

fn format_stream_text(bytes: Vec<u8>) -> Vec<u8> {
    if !bytes.contains(&8) && !bytes.contains(&b'\r') {
        return bytes;
    }
    let text: Vec<u16> = String::from_utf8_lossy(&bytes).encode_utf16().collect();
    String::from_utf16_lossy(&fix_carriage_return(fix_backspace(text))).into_bytes()
}

/// `fixBackspace`: `/[^\n]\x08/g` removed until nothing changes, on UTF-16 units as JavaScript strings are.
fn fix_backspace(mut text: Vec<u16>) -> Vec<u16> {
    loop {
        let mut kept = Vec::with_capacity(text.len());
        let mut index = 0;
        while index < text.len() {
            if text[index] != u16::from(b'\n') && text.get(index + 1) == Some(&8) {
                index += 2;
                continue;
            }
            kept.push(text[index]);
            index += 1;
        }
        if kept.len() == text.len() {
            return kept;
        }
        text = kept;
    }
}

const CR: u16 = b'\r' as u16;
const LF: u16 = b'\n' as u16;
const DOLLAR: u16 = b'$' as u16;

/// JavaScript's line terminators, which `.`, `^` and `$` of a multiline regex stop at.
fn is_line_terminator(unit: u16) -> bool {
    matches!(unit, CR | LF | 0x2028 | 0x2029)
}

/// `fixCarriageReturn`, on UTF-16 units.
fn fix_carriage_return(text: Vec<u16>) -> Vec<u16> {
    // `/\r+\n/gm` becomes a newline.
    let mut txt = Vec::with_capacity(text.len());
    let mut index = 0;
    while index < text.len() {
        let run = text[index..].iter().take_while(|unit| **unit == CR).count();
        if run > 0 && text.get(index + run) != Some(&LF) {
            txt.extend_from_slice(&text[index..index + run]);
        }
        index += run;
        if let Some(unit) = text.get(index) {
            txt.push(*unit);
            index += 1;
        }
    }
    if !txt.contains(&CR) {
        return txt;
    }
    let is_line_break = |unit: &u16| matches!(*unit, LF | 0x2028 | 0x2029);
    if txt.contains(&DOLLAR) && txt.split(is_line_break).any(|line| line.contains(&CR) && line.contains(&DOLLAR)) {
        return fix_dollar_carriage_returns(txt);
    }
    let pending_carriage_return = txt.ends_with(&[CR]) && !txt.ends_with(&[CR, CR]);
    if pending_carriage_return {
        txt.pop();
    }
    let mut result = Vec::with_capacity(txt.len());
    let mut line_start = 0;
    for (index, unit) in txt.iter().enumerate() {
        if is_line_break(unit) {
            result.extend(overwrite_line(&txt[line_start..index]));
            result.push(*unit);
            line_start = index + 1;
        }
    }
    result.extend(overwrite_line(&txt[line_start..]));
    if pending_carriage_return {
        result.push(CR);
    }
    result
}

/// Later `\r`-separated segments overwrite prefixes; only the uncovered suffix of each earlier segment stays.
fn overwrite_line(line: &[u16]) -> Vec<u16> {
    if !line.contains(&CR) {
        return line.to_vec();
    }
    let mut fragments = Vec::new();
    let mut length = 0;
    for segment in line.split(|unit| *unit == CR).filter(|segment| !segment.is_empty()).rev() {
        if segment.len() > length {
            fragments.extend_from_slice(&segment[length..]);
            length = segment.len();
        }
    }
    fragments
}

/// The legacy loop of `fixCarriageReturn` for lines with `$`, whose `String.replace` reads `$` patterns in the
/// replacement text.
fn fix_dollar_carriage_returns(mut txt: Vec<u16>) -> Vec<u16> {
    let line_start = |txt: &[u16], index: usize| index == 0 || is_line_terminator(txt[index - 1]);
    let run_end = |txt: &[u16], start: usize| start + txt[start..].iter().take_while(|unit| !is_line_terminator(**unit)).count();
    // `txt.search(/\r[^$]/g) > -1`
    while txt.windows(2).any(|pair| pair[0] == CR && pair[1] != DOLLAR) {
        // `/^(.*)\r+/m`: the first line start whose text runs into a `\r`.
        let (base_start, base_end) = (0..txt.len()).filter(|index| line_start(&txt, *index)).map(|start| (start, run_end(&txt, start))).find(|(_, end)| txt.get(*end) == Some(&CR)).expect("a \\r follows a line's text");
        let base = txt[base_start..base_end].to_vec();
        // `/\r+(.*)$/m`: the text after the first run of `\r`.
        let first_cr = txt.iter().position(|unit| *unit == CR).expect("checked by the loop");
        let after_crs = first_cr + txt[first_cr..].iter().take_while(|unit| **unit == CR).count();
        let insert_end = run_end(&txt, after_crs);
        let mut insert = txt[after_crs..insert_end].to_vec();
        insert.extend_from_slice(base.get(insert.len()..).unwrap_or_default());
        // `txt.replace(/\r+.*$/m, '\r')`
        txt.splice(first_cr..insert_end, [CR]);
        // `.replace(/^.*\r/m, insert)`
        let (start, end) = (0..txt.len()).filter(|index| line_start(&txt, *index)).map(|start| (start, run_end(&txt, start))).find(|(_, end)| txt.get(*end) == Some(&CR)).expect("the \\r left above");
        let replacement = js_substitution(&insert, &txt, start, end + 1);
        txt.splice(start..end + 1, replacement);
    }
    txt
}

/// `GetSubstitution` of `String.prototype.replace` for a pattern without groups.
fn js_substitution(replacement: &[u16], text: &[u16], start: usize, end: usize) -> Vec<u16> {
    let mut result = Vec::new();
    let mut index = 0;
    while index < replacement.len() {
        let next = replacement.get(index + 1).copied();
        match (replacement[index], next) {
            (DOLLAR, Some(DOLLAR)) => result.push(DOLLAR),
            (DOLLAR, Some(0x26)) => result.extend_from_slice(&text[start..end]),
            (DOLLAR, Some(0x60)) => result.extend_from_slice(&text[..start]),
            (DOLLAR, Some(0x27)) => result.extend_from_slice(&text[end..]),
            (unit, _) => {
                result.push(unit);
                index += 1;
                continue;
            }
        }
        index += 2;
    }
    result
}

fn object_or_empty(value: &Value) -> Value {
    match value {
        Value::Object(_) => value.clone(),
        _ => json!({}),
    }
}

/// A partial metadata edit: each key set, a `null` one removed.
fn merged(old: &Value, partial: &Value) -> Value {
    let mut map = old.as_object().cloned().unwrap_or_default();
    for (key, value) in partial.as_object().into_iter().flatten() {
        match value {
            Value::Null => _ = map.remove(key),
            value => _ = map.insert(key.clone(), value.clone()),
        }
    }
    Value::Object(map)
}

/// The metadata without the keys a `TransientMetadata` (`{ key: true }`) marks.
fn without_keys(metadata: &Value, transient: &Value) -> Value {
    let map: Map<String, Value> = metadata.as_object().into_iter().flatten().filter(|(key, _)| transient[key.as_str()] != true).map(|(key, value)| (key.clone(), value.clone())).collect();
    Value::Object(map)
}

#[cfg(test)]
mod tests;