Cotton code
848 lines · 35.7 KB · RustRaw
//! What each formatting button does to a text and its selection.//!//! Every action answers the whole new text, the ONE replacement that makes it//! from the old (`replace`: a UTF-16 range of the old text and what goes//! there, so the phone applies it as an ordinary edit and its own undo and//! redo keep it), and the new selection.//!//! - **Inline** (`bold`, `italic`, `underline`, `strike`, `highlight`,//!   `code`): over a selection, wrap each selected line's words; when the//!   selection is already inside that style, take it off. A cursor inside a//!   word wraps the word; elsewhere it puts an empty pair with the cursor//!   between, so what is typed next wears the style.//! - **Blocks** (`heading` with `level` 1–6 or 0 for none, `bullet`,//!   `numbered`, `check`, `quote`, `paragraph`): each selected line becomes//!   that kind, keeping its words and indent; when every line already is,//!   they go back to paragraphs.//! - `tick`: a check item at the selection's start ticks or unticks.//! - `return`: a new line that continues a list, a check list or a quote//!   (the next number; an unticked box), keeping the indent; on an empty item//!   it ends the list (or steps out one level when indented). Inside code it//!   keeps the indent.//! - `indent` / `outdent`: a list item moves one level (four spaces) in or out.//! - `move_up` / `move_down`: the selected lines swap with the line above or//!   below; the selection moves with them.//! - `link` (with an optional `url`): the selection becomes `[words](url)`;//!   with no url the cursor waits inside the parentheses. Inside a link it//!   takes the link off, keeping the words.//! - `divider`: a rule on its own line after the current one.//! - `code_block`: fences around the selected lines; inside a code block, the//!   fences go.use serde::{Deserialize, Serialize};use super::inline::Piece;use super::style::{self, Kind, Line, Style};use super::table;use super::{byte_at, Offsets, Selection};#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(tag = "action", rename_all = "snake_case")]pub enum Action {    Return,    Bold,    Italic,    Underline,    Strike,    Highlight,    Code,    Heading {        #[serde(default = "one")]        level: u8,    },    Paragraph,    Bullet,    Numbered,    Check,    Tick,    Quote,    Indent,    Outdent,    MoveUp,    MoveDown,    Link {        #[serde(default)]        url: Option<String>,    },    Divider,    CodeBlock,    /// A new table on its own line (two columns, a header and one row unless    /// said), the cursor in its first header cell.    Table {        #[serde(default = "two")]        columns: usize,        #[serde(default = "one_row")]        rows: usize,    },    /// A row under the cursor's row (`above` for over it); the cursor goes to    /// its first cell. Return in a table does this too.    TableRowAdd {        #[serde(default)]        above: bool,    },    /// The cursor's body row goes (a header stays).    TableRowRemove,    /// A column after the cursor's (`before` for ahead of it).    TableColumnAdd {        #[serde(default)]        before: bool,    },    /// The cursor's column goes; the last column takes the table with it.    TableColumnRemove,    /// One cell's words, by row (0 the header) and column, in the table the    /// selection is in: what the phone's cell editor commits.    TableCell { row: usize, column: usize, text: String },    /// A picture on its own line after the cursor's line: `![alt](src)`.    Picture {        src: String,        #[serde(default)]        alt: String,    },    /// The width of the picture on the cursor's line: `small`, `medium` or    /// `full`, written as the reference app writes it (`<!-- {"width":160} -->`).    PictureWidth { width: String },    /// A link to a note: `[[title]]` at the cursor; with no title, the    /// selection inside `[[…]]` (or `[[]]` with the cursor between).    NoteLink {        #[serde(default)]        title: Option<String>,    },    /// Fold the cursor's section: the text is not changed; the answer says    /// which fold (`notes.format` answers `fold`).    Fold,    /// Today's date written at the cursor (over the selection): `words` is the    /// date as the caller says it (`notes.format` fills it in the person's zone).    Today {        #[serde(default)]        words: String,    },}fn one() -> u8 {    1}fn two() -> usize {    2}fn one_row() -> usize {    1}/// A replacement in the old text, UTF-16.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Replace {    pub start: u32,    pub end: u32,    pub with: String,}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Edited {    pub text: String,    /// None when the action changed nothing.    pub replace: Option<Replace>,    pub selection: Selection,}/// Apply one button to `text` at `selection` (UTF-16).pub fn apply(text: &str, selection: Selection, action: &Action) -> Edited {    let (lo, hi) = (selection.start.min(selection.end), selection.start.max(selection.end));    let start = byte_at(text, lo);    let end = byte_at(text, hi);    let (new_text, new_start, new_end) = match action {        Action::Return => press_return(text, start, end),        Action::Bold => inline(text, start, end, "**", Style::Bold),        Action::Italic => inline(text, start, end, "*", Style::Italic),        Action::Underline => inline(text, start, end, "~", Style::Underline),        Action::Strike => inline(text, start, end, "~~", Style::Strike),        Action::Highlight => inline(text, start, end, "==", Style::Highlight),        Action::Code => inline(text, start, end, "`", Style::Code),        Action::Heading { level } => blocks(text, start, end, Target::Heading((*level).min(6))),        Action::Paragraph => blocks(text, start, end, Target::Heading(0)),        Action::Bullet => blocks(text, start, end, Target::Bullet),        Action::Numbered => blocks(text, start, end, Target::Numbered),        Action::Check => blocks(text, start, end, Target::Check),        Action::Quote => blocks(text, start, end, Target::Quote),        Action::Tick => tick(text, start, end),        Action::Indent => indent(text, start, end, true),        Action::Outdent => indent(text, start, end, false),        Action::MoveUp => move_lines(text, start, end, true),        Action::MoveDown => move_lines(text, start, end, false),        Action::Link { url } => link(text, start, end, url.as_deref()),        Action::Divider => divider(text, start, end),        Action::CodeBlock => code_block(text, start, end),        Action::Table { columns, rows } => new_table(text, start, (*columns).clamp(1, 20), (*rows).min(200)),        Action::TableRowAdd { above } => table_edit(text, start, end, Grid::AddRow(*above)),        Action::TableRowRemove => table_edit(text, start, end, Grid::RemoveRow),        Action::TableColumnAdd { before } => table_edit(text, start, end, Grid::AddColumn(*before)),        Action::TableColumnRemove => table_edit(text, start, end, Grid::RemoveColumn),        Action::TableCell { row, column, text: words } => table_edit(text, start, end, Grid::Cell(*row, *column, words.clone())),        Action::Picture { src, alt } => picture(text, start, src, alt),        Action::PictureWidth { width } => picture_width(text, start, end, width),        Action::NoteLink { title } => note_link(text, start, end, title.as_deref()),        Action::Fold => (text.to_string(), start, end),        Action::Today { words } => {            let at = start + words.len();            (format!("{}{words}{}", &text[..start], &text[end..]), at, at)        }    };    finish(text, new_text, new_start, new_end)}fn finish(old: &str, text: String, start: usize, end: usize) -> Edited {    let offsets = Offsets::new(&text);    let selection = Selection { start: offsets.u16(start.min(text.len())), end: offsets.u16(end.min(text.len())) };    let replace = diff(old, &text);    Edited { text, replace, selection }}/// The one replacement that turns `old` into `new`: the common prefix and/// suffix kept, on char boundaries.fn diff(old: &str, new: &str) -> Option<Replace> {    if old == new {        return None;    }    let mut prefix = old.bytes().zip(new.bytes()).take_while(|(a, b)| a == b).count();    while !old.is_char_boundary(prefix) || !new.is_char_boundary(prefix) {        prefix -= 1;    }    let max_suffix = old.len().min(new.len()) - prefix;    let mut suffix = old.bytes().rev().zip(new.bytes().rev()).take(max_suffix).take_while(|(a, b)| a == b).count();    while !old.is_char_boundary(old.len() - suffix) || !new.is_char_boundary(new.len() - suffix) {        suffix -= 1;    }    let offsets = Offsets::new(old);    Some(Replace { start: offsets.u16(prefix), end: offsets.u16(old.len() - suffix), with: new[prefix..new.len() - suffix].to_string() })}// ── edits as a list of operations ───────────────────────────────────────────/// Non-overlapping replacements in byte offsets of the old text, with the/// map of old positions to new.#[derive(Default)]struct Ops {    ops: Vec<(usize, usize, String)>,}#[derive(Clone, Copy, PartialEq)]enum Bias {    /// A position at an insertion lands before what is inserted.    Before,    /// …or after it.    After,}impl Ops {    fn put(&mut self, at: usize, delete: usize, insert: impl Into<String>) {        self.ops.push((at, delete, insert.into()));    }    fn sorted(&self) -> Vec<&(usize, usize, String)> {        let mut ops: Vec<_> = self.ops.iter().collect();        ops.sort_by_key(|op| (op.0, op.1));        ops    }    fn apply(&self, text: &str) -> String {        let mut out = String::with_capacity(text.len() + 16);        let mut at = 0;        for (start, delete, insert) in self.sorted() {            out.push_str(&text[at..*start]);            out.push_str(insert);            at = start + delete;        }        out.push_str(&text[at..]);        out    }    fn map(&self, pos: usize, bias: Bias) -> usize {        let mut shift: isize = 0;        for (start, delete, insert) in self.sorted() {            let (start, delete) = (*start, *delete);            if pos < start {                break;            }            if delete == 0 && pos == start {                if bias == Bias::Before {                    break;                }                shift += insert.len() as isize;                continue;            }            if pos < start + delete {                // Inside what is deleted: after what replaces it.                return (start as isize + shift) as usize + insert.len();            }            shift += insert.len() as isize - delete as isize;        }        (pos as isize + shift) as usize    }}fn line_at(lines: &[Line], at: usize) -> usize {    lines.partition_point(|line| line.end < at).min(lines.len() - 1)}/// The lines a selection covers: a selection ending at a line's very start/// leaves that line out.fn selected(lines: &[Line], start: usize, end: usize) -> (usize, usize) {    let first = line_at(lines, start);    let mut last = line_at(lines, end);    if end > start && last > first && lines[last].start == end {        last -= 1;    }    (first, last)}// ── inline ──────────────────────────────────────────────────────────────────fn inline(text: &str, start: usize, end: usize, mark: &str, style: Style) -> (String, usize, usize) {    let lines = style::lines(text);    let len = mark.len();    // Inside that style already: take it off.    let at = line_at(&lines, start);    if line_at(&lines, end) == at {        let (pieces, _) = style::inline_of(text, &lines[at]);        let around = pieces.iter().find_map(|piece| match piece {            Piece::Run { start: s, end: e, style: st, .. } if *st == style && *s <= start && end <= *e && *s >= len && text.get(*s - len..*s) == Some(mark) && text.get(*e..*e + len) == Some(mark) => Some((*s, *e)),            _ => None,        });        if let Some((s, e)) = around {            let mut ops = Ops::default();            ops.put(s - len, len, "");            ops.put(e, len, "");            return (ops.apply(text), ops.map(start, Bias::After), ops.map(end, Bias::Before));        }    }    let mut ops = Ops::default();    if start == end {        let before = text[..start].chars().next_back();        let after = text[start..].chars().next();        if before.is_some_and(char::is_alphanumeric) && after.is_some_and(char::is_alphanumeric) {            let line = &lines[at];            let word_start = text[line.content..start].char_indices().rev().take_while(|(_, c)| c.is_alphanumeric()).last().map(|(k, _)| line.content + k).unwrap_or(start);            let word_end = start + text[start..line.end].char_indices().find(|(_, c)| !c.is_alphanumeric()).map(|(k, _)| k).unwrap_or(line.end - start);            ops.put(word_start, 0, mark);            ops.put(word_end, 0, mark);            return (ops.apply(text), start + len, start + len);        }        ops.put(start, 0, format!("{mark}{mark}"));        return (ops.apply(text), start + len, start + len);    }    let (first, last) = selected(&lines, start, end);    let mut new_start = None;    let mut new_end = end;    for line in &lines[first..=last] {        let from = start.max(line.content);        let to = end.min(line.end);        if from >= to {            continue;        }        let words = &text[from..to];        let lead = words.len() - words.trim_start().len();        let trail = words.len() - words.trim_end().len();        if lead + trail >= words.len() {            continue;        }        ops.put(from + lead, 0, mark);        ops.put(to - trail, 0, mark);        if new_start.is_none() {            new_start = Some(from + lead);        }        new_end = to - trail;    }    match new_start {        None => (text.to_string(), start, end),        Some(s) => (ops.apply(text), ops.map(s, Bias::After), ops.map(new_end, Bias::Before)),    }}// ── blocks ──────────────────────────────────────────────────────────────────#[derive(Clone, Copy, PartialEq)]enum Target {    /// 0 is a plain paragraph.    Heading(u8),    Bullet,    Numbered,    Check,    Quote,}fn is_target(line: &Line, target: Target) -> bool {    match target {        Target::Heading(0) => line.kind == Kind::Paragraph,        Target::Heading(level) => line.kind == Kind::Heading && line.level == Some(level),        Target::Bullet => line.kind == Kind::Bullet,        Target::Numbered => line.kind == Kind::Numbered,        Target::Check => line.kind == Kind::Check,        Target::Quote => line.kind == Kind::Quote,    }}fn blocks(text: &str, start: usize, end: usize, target: Target) -> (String, usize, usize) {    let lines = style::lines(text);    let (first, last) = selected(&lines, start, end);    let chosen: Vec<usize> = (first..=last).filter(|&k| !matches!(lines[k].kind, Kind::Code | Kind::Fence | Kind::Divider) && (lines[k].kind != Kind::Blank || first == last)).collect();    if chosen.is_empty() {        return (text.to_string(), start, end);    }    let undo = target != Target::Heading(0) && chosen.iter().all(|&k| is_target(&lines[k], target));    // The number a new numbered run starts at: one after the item above it.    let mut number = match first.checked_sub(1).map(|k| &lines[k]) {        Some(above) if above.kind == Kind::Numbered && above.depth == lines[first].depth => above.number.unwrap_or(0) + 1,        _ => 1,    };    let mut ops = Ops::default();    for &k in &chosen {        let line = &lines[k];        let indent = &text[line.start..line.indent_end];        let keep_indent = !matches!(target, Target::Heading(_) | Target::Quote) || undo && !matches!(line.kind, Kind::Heading | Kind::Quote);        let prefix = if undo {            if keep_indent { indent.to_string() } else { String::new() }        } else {            match target {                Target::Heading(0) => String::new(),                Target::Heading(level) => format!("{} ", "#".repeat(level as usize)),                Target::Bullet => format!("{indent}{} ", bullet_char(text, line)),                Target::Check => format!("{indent}{} [ ] ", bullet_char(text, line)),                Target::Numbered => {                    let said = format!("{indent}{number}. ");                    number += 1;                    said                }                Target::Quote => "> ".to_string(),            }        };        ops.put(line.start, line.content - line.start, prefix);    }    let edited = ops.apply(text);    (edited, ops.map(start, Bias::After), ops.map(end, Bias::After))}fn bullet_char(text: &str, line: &Line) -> char {    match line.kind {        Kind::Bullet | Kind::Check => text[line.indent_end..].chars().next().unwrap_or('-'),        _ => '-',    }}fn tick(text: &str, start: usize, end: usize) -> (String, usize, usize) {    let lines = style::lines(text);    let line = &lines[line_at(&lines, start)];    if line.kind != Kind::Check {        return (text.to_string(), start, end);    }    let box_at = line.indent_end + 3;    let mark = if line.checked == Some(true) { " " } else { "x" };    let mut edited = text.to_string();    edited.replace_range(box_at..box_at + 1, mark);    (edited, start, end)}// ── return ──────────────────────────────────────────────────────────────────fn press_return(text: &str, start: usize, end: usize) -> (String, usize, usize) {    // A selection is replaced by the line break.    let (text, at) = if end > start { (format!("{}{}", &text[..start], &text[end..]), start) } else { (text.to_string(), start) };    let lines = style::lines(&text);    let line = &lines[line_at(&lines, at)];    let plain_break = |text: &str, insert: String| {        let mut out = String::with_capacity(text.len() + insert.len());        out.push_str(&text[..at]);        out.push_str(&insert);        out.push_str(&text[at..]);        (out, at + insert.len(), at + insert.len())    };    let indent = text[line.start..line.indent_end].to_string();    match line.kind {        Kind::Table | Kind::TableRule => table_edit(&text, at, at, Grid::AddRow(false)),        Kind::Code => plain_break(&text, format!("\n{indent}")),        Kind::Bullet | Kind::Check | Kind::Numbered | Kind::Quote if at >= line.content => {            let empty = text[line.content..line.end].trim().is_empty();            if empty {                if line.kind != Kind::Quote && line.depth > 0 {                    return indent_lines(&text, line_at(&lines, at), line_at(&lines, at), false, at, at);                }                // End the list: the marker goes, the line stays.                let mut out = text.clone();                out.replace_range(line.start..line.end, "");                return (out, line.start, line.start);            }            let marker = match line.kind {                Kind::Bullet => format!("{indent}{} ", bullet_char(&text, line)),                Kind::Check => format!("{indent}{} [ ] ", bullet_char(&text, line)),                Kind::Numbered => {                    let delim = text[line.indent_end..line.content].trim_end().chars().last().unwrap_or('.');                    format!("{indent}{}{delim} ", line.number.unwrap_or(0) + 1)                }                _ => text[line.start..line.content].to_string(),            };            let words = text[at..line.end].trim_start().len();            let skip = (line.end - at) - words;            let mut out = String::with_capacity(text.len() + marker.len() + 1);            out.push_str(&text[..at]);            out.push('\n');            out.push_str(&marker);            let caret = out.len();            out.push_str(&text[at + skip..]);            // Renumbering touches only the items after the new one.            let out = if line.kind == Kind::Numbered { renumber(&out, line_at(&lines, at) + 1) } else { out };            (out, caret, caret)        }        _ => plain_break(&text, "\n".to_string()),    }}/// Renumber the numbered items after line `from` at the same depth, while/// the list runs on; the edit never moves text before `from`'s line end.fn renumber(text: &str, from: usize) -> String {    let lines = style::lines(text);    let Some(head) = lines.get(from) else { return text.to_string() };    if head.kind != Kind::Numbered {        return text.to_string();    }    let mut next = head.number.unwrap_or(1) + 1;    let mut ops = Ops::default();    for line in &lines[from + 1..] {        if line.depth > head.depth && (line.kind.is_item() || line.kind == Kind::Paragraph) {            continue;        }        if line.kind != Kind::Numbered || line.depth != head.depth {            break;        }        let digits = text[line.indent_end..].bytes().take_while(u8::is_ascii_digit).count();        let said = next.to_string();        if text[line.indent_end..line.indent_end + digits] != said {            ops.put(line.indent_end, digits, said);        }        next += 1;    }    ops.apply(text)}// ── indent, move ────────────────────────────────────────────────────────────const INDENT: &str = "    ";fn indent(text: &str, start: usize, end: usize, deeper: bool) -> (String, usize, usize) {    let lines = style::lines(text);    let (first, last) = selected(&lines, start, end);    indent_lines(text, first, last, deeper, start, end)}fn indent_lines(text: &str, first: usize, last: usize, deeper: bool, start: usize, end: usize) -> (String, usize, usize) {    let lines = style::lines(text);    let mut ops = Ops::default();    for line in &lines[first..=last] {        if !line.kind.is_item() {            continue;        }        if deeper {            ops.put(line.start, 0, INDENT);        } else {            let mut cols = 0;            let mut bytes = 0;            for b in text[line.start..line.indent_end].bytes() {                cols += if b == b'\t' { 4 } else { 1 };                bytes += 1;                if cols >= 4 {                    break;                }            }            if bytes > 0 {                ops.put(line.start, bytes, "");            }        }    }    (ops.apply(text), ops.map(start, Bias::After), ops.map(end, Bias::After))}fn move_lines(text: &str, start: usize, end: usize, up: bool) -> (String, usize, usize) {    let lines = style::lines(text);    let (first, last) = selected(&lines, start, end);    if (up && first == 0) || (!up && last + 1 >= lines.len()) {        return (text.to_string(), start, end);    }    let block = &text[lines[first].start..lines[last].end];    if up {        let above = &lines[first - 1];        let neighbour = &text[above.start..above.end];        let edited = format!("{}{block}\n{neighbour}{}", &text[..above.start], &text[lines[last].end..]);        let shift = lines[first].start - above.start;        (edited, start - shift, end - shift)    } else {        let below = &lines[last + 1];        let neighbour = &text[below.start..below.end];        let edited = format!("{}{neighbour}\n{block}{}", &text[..lines[first].start], &text[below.end..]);        let shift = neighbour.len() + 1;        (edited, start + shift, end + shift)    }}// ── link, divider, code block ───────────────────────────────────────────────fn link(text: &str, start: usize, end: usize, url: Option<&str>) -> (String, usize, usize) {    let lines = style::lines(text);    let line = &lines[line_at(&lines, start)];    let (pieces, _) = style::inline_of(text, line);    // Inside a written link: keep its words, take the link off.    let around = pieces.iter().find_map(|piece| match piece {        Piece::Run { start: s, end: e, style: Style::Link, .. } if *s <= start && end <= *e && *s > 0 && text.as_bytes()[*s - 1] == b'[' => Some((*s, *e)),        _ => None,    });    if let Some((s, e)) = around {        let close = text[e..line.end].find(')').map(|k| e + k + 1).unwrap_or(e);        let mut ops = Ops::default();        ops.put(s - 1, 1, "");        ops.put(e, close - e, "");        return (ops.apply(text), ops.map(start, Bias::After), ops.map(end, Bias::Before));    }    let end = end.min(line.end).max(start);    let url = url.map(str::trim).unwrap_or_default();    let label = if start == end { url.to_string() } else { String::new() };    let mut ops = Ops::default();    ops.put(start, 0, format!("[{label}"));    ops.put(end, 0, format!("]({url})"));    let edited = ops.apply(text);    if url.is_empty() {        // The cursor waits inside the parentheses.        let caret = start + 1 + (end - start) + 2;        (edited, caret, caret)    } else if start == end {        (edited, start + 1, start + 1 + label.len())    } else {        let after = start + 1 + (end - start) + 2 + url.len() + 1;        (edited, after, after)    }}fn divider(text: &str, start: usize, _end: usize) -> (String, usize, usize) {    let lines = style::lines(text);    let at = line_at(&lines, start);    let line = &lines[at];    let above_blank = at == 0 || lines[at - 1].kind == Kind::Blank;    if line.kind == Kind::Blank {        let lead = if above_blank { "" } else { "\n" };        let tail = if line.end == text.len() { "\n" } else { "" };        let edited = format!("{}{lead}---{tail}{}", &text[..line.start], &text[line.end..]);        let caret = (line.start + lead.len() + 4).min(edited.len());        return (edited, caret, caret);    }    let tail = if line.end == text.len() { "\n" } else { "" };    let insert = format!("\n\n---{tail}");    let edited = format!("{}{insert}{}", &text[..line.end], &text[line.end..]);    let caret = (line.end + insert.len() + if tail.is_empty() { 1 } else { 0 }).min(edited.len());    (edited, caret, caret)}fn code_block(text: &str, start: usize, end: usize) -> (String, usize, usize) {    let lines = style::lines(text);    let at = line_at(&lines, start);    // Inside a block: the fences go.    if let Some((block_start, block_end)) = lines[at].block {        let fences: Vec<&Line> = lines.iter().filter(|line| line.kind == Kind::Fence && line.start >= block_start && line.end <= block_end).collect();        let mut ops = Ops::default();        for fence in fences {            let through = if fence.end < text.len() { fence.end + 1 } else { fence.end };            let from = if fence.end >= text.len() && fence.start > 0 { fence.start - 1 } else { fence.start };            ops.put(from, through - from, "");        }        return (ops.apply(text), ops.map(start, Bias::After), ops.map(end, Bias::After));    }    let (first, last) = selected(&lines, start, end);    let mut ops = Ops::default();    ops.put(lines[first].start, 0, "```\n");    ops.put(lines[last].end, 0, "\n```");    (ops.apply(text), ops.map(start, Bias::After), ops.map(end, Bias::Before))}// ── tables, pictures ────────────────────────────────────────────────────────/// Put a block of `lines` on its own line(s) at the cursor's line: in place/// of a blank line, else after the line with a blank line between. Answers/// the new text and where the block starts.fn place_block(text: &str, start: usize, block: &str) -> (String, usize) {    let lines = style::lines(text);    let at = line_at(&lines, start);    let line = &lines[at];    let above_blank = at == 0 || lines[at - 1].kind == Kind::Blank;    if line.kind == Kind::Blank {        let lead = if above_blank { "" } else { "\n" };        let tail = if line.end == text.len() { "\n" } else { "" };        let edited = format!("{}{lead}{block}{tail}{}", &text[..line.start], &text[line.end..]);        return (edited, line.start + lead.len());    }    let tail = if line.end == text.len() { "\n" } else { "" };    let edited = format!("{}\n\n{block}{tail}{}", &text[..line.end], &text[line.end..]);    (edited, line.end + 2)}fn new_table(text: &str, start: usize, columns: usize, rows: usize) -> (String, usize, usize) {    let empty: Vec<Vec<String>> = (0..=rows).map(|_| vec![String::new(); columns]).collect();    let block = table::write(&vec![table::Align::None; columns], &empty);    let (edited, at) = place_block(text, start, &block);    // The first header cell's words go after `| `.    (edited, at + 2, at + 2)}fn picture(text: &str, start: usize, src: &str, alt: &str) -> (String, usize, usize) {    let alt = alt.replace(['[', ']', '\n'], " ");    let src = src.trim().replace(' ', "%20");    let block = format!("![{alt}]({src})");    let (edited, at) = place_block(text, start, &block);    let after = (at + block.len() + 1).min(edited.len());    (edited, after, after)}/// The picture line the cursor is on, its width written anew.fn picture_width(text: &str, start: usize, end: usize, width: &str) -> (String, usize, usize) {    let lines = style::lines(text);    let Some(line) = lines.iter().find(|line| line.kind == Kind::Picture && line.start <= start && start <= line.end) else {        return (text.to_string(), start, end);    };    let Some((_, close, _)) = super::inline::link_at(text, line.indent_end + 1, line.end) else { return (text.to_string(), start, end) };    let old = super::inline::width_comment(text, close, line.end).map_or(0, |(len, _)| len);    let points = style::WIDTHS.iter().find(|(name, _)| *name == width).and_then(|(_, points)| *points);    let comment = points.map(|points| format!("<!-- {{\"width\":{points}}} -->")).unwrap_or_default();    let edited = format!("{}{comment}{}", &text[..close], &text[close + old..]);    let at = (close + comment.len()).min(edited.len());    (edited, at, at)}/// `[[title]]` at the cursor, or the selection made a link.fn note_link(text: &str, start: usize, end: usize, title: Option<&str>) -> (String, usize, usize) {    let picked = text[start..end].trim();    let title = title.map(str::trim).filter(|t| !t.is_empty()).map(str::to_string).or_else(|| (!picked.is_empty() && !picked.contains('\n')).then(|| picked.to_string()));    match title {        Some(title) => {            let link = format!("[[{}]]", title.replace(['[', ']', '\n'], " "));            let edited = format!("{}{link}{}", &text[..start], &text[end..]);            let at = start + link.len();            (edited, at, at)        }        None => {            let edited = format!("{}[[]]{}", &text[..start], &text[end..]);            (edited, start + 2, start + 2)        }    }}enum Grid {    AddRow(bool),    RemoveRow,    AddColumn(bool),    RemoveColumn,    Cell(usize, usize, String),}/// The cell column a byte position is in, on a table row line.fn column_at(text: &str, line: &Line, at: usize) -> usize {    let cells = table::cells(text, line.start, line.end);    let mut column = 0;    for (index, cell) in cells.iter().enumerate() {        if at >= cell.start || index == 0 {            column = index;        }        // Between two cells, past the pipe, is the next one.        if let Some(next) = cells.get(index + 1) {            let bar = text[cell.end..next.start].find('|').map(|k| cell.end + k);            if bar.is_some_and(|bar| at > bar) {                column = index + 1;            }        }    }    column.min(cells.len().saturating_sub(1))}fn table_edit(text: &str, start: usize, end: usize, edit: Grid) -> (String, usize, usize) {    let lines = style::lines(text);    let here = line_at(&lines, start);    let Some(block) = lines[here].block.filter(|_| matches!(lines[here].kind, Kind::Table | Kind::TableRule)) else {        return (text.to_string(), start, end);    };    let rows: Vec<&Line> = lines.iter().filter(|line| line.block == Some(block) && line.kind == Kind::Table).collect();    let rule = lines.iter().find(|line| line.block == Some(block) && line.kind == Kind::TableRule).expect("a table has its delimiter line");    let mut align = table::delimiter(text, rule.start, rule.end).unwrap_or_default();    let columns = align.len();    let mut grid: Vec<Vec<String>> = rows        .iter()        .map(|line| {            let mut row: Vec<String> = table::cells(text, line.start, line.end).into_iter().map(|cell| text[cell.start..cell.end].to_string()).collect();            row.resize(columns.max(row.len()), String::new());            row        })        .collect();    let row_here = lines[here].row.unwrap_or(0);    let column_here = if lines[here].kind == Kind::Table { column_at(text, &lines[here], start) } else { 0 };    // The cell the cursor lands in afterwards, by (row, column).    let land;    match edit {        Grid::Cell(row, column, words) => {            let Some(line) = rows.get(row) else { return (text.to_string(), start, end) };            let cells = table::cells(text, line.start, line.end);            let words = table::escape(words.trim());            if let Some(cell) = cells.get(column) {                let mut ops = Ops::default();                ops.put(cell.start, cell.end - cell.start, words.clone());                let caret = cell.start + words.len();                return (ops.apply(text), caret, caret);            }            if column >= columns {                return (text.to_string(), start, end);            }            // A short row gains the cells up to this one.            let row_cells = &mut grid[row];            row_cells[column] = words;            land = (row, column);        }        Grid::AddRow(above) => {            let at = if above { row_here.max(1) } else { row_here + 1 };            grid.insert(at, vec![String::new(); columns]);            land = (at, 0);        }        Grid::RemoveRow => {            if row_here == 0 || lines[here].kind != Kind::Table {                return (text.to_string(), start, end);            }            grid.remove(row_here);            land = (row_here.min(grid.len() - 1), column_here);        }        Grid::AddColumn(before) => {            let at = if before { column_here } else { column_here + 1 };            for row in grid.iter_mut() {                row.insert(at.min(row.len()), String::new());            }            align.insert(at.min(align.len()), table::Align::None);            land = (row_here, at);        }        Grid::RemoveColumn => {            if columns <= 1 {                // The last column takes the table with it, and its line break.                let through = if block.1 < text.len() { block.1 + 1 } else { block.1 };                let edited = format!("{}{}", &text[..block.0], &text[through..]);                return (edited, block.0, block.0);            }            for row in grid.iter_mut() {                if column_here < row.len() {                    row.remove(column_here);                }            }            align.remove(column_here);            land = (row_here, column_here.min(columns - 2));        }    }    let written = table::write(&align, &grid);    let edited = format!("{}{written}{}", &text[..block.0], &text[block.1..]);    // Find the landing cell in what was written.    let lines_after = style::lines(&edited);    let caret = lines_after        .iter()        .filter(|line| line.kind == Kind::Table && line.block.is_some_and(|b| b.0 == block.0))        .nth(land.0)        .and_then(|line| table::cells(&edited, line.start, line.end).get(land.1).map(|cell| cell.end))        .unwrap_or(block.0);    (edited, caret, caret)}