//! Editing commands over the flat body ([`note_model::flat`]): the keymap semantics of //! prosemirror-commands / prosemirror-schema-list and the app's toggles, as edits of //! text, separators and the wrap paths separators carry. //! //! Structure is relative: a block shares [`keep`] levels with the block before it //! (whole containers, and for a list the item), then opens the rest. Commands change //! wraps and keeps of a block range and restore the keep of the block after it, so //! nothing outside the range moves. //! //! A command takes the context and `apply`. With `apply == false` it only reports //! whether it would do something and must not edit (toolbar state). With `apply` it //! edits through the model's primitives and sets `cx.sel`. use note_model::flat::{self, Attrs, FlatBlock, Kind as Leaf, Wrap, default_join}; use note_model::write::{Block, Inline}; use loro::{LoroValue, TextDelta}; use super::doc::Kind; use super::marks::{Link, MarkType, Marks}; use super::model::{Blk, INLINE, Model, Seg}; use super::pos::{self, Pos, Selection}; pub struct Cx<'a> { pub m: &'a Model, pub sel: Selection, /// Marks for the next typed text at a collapsed cursor (PM stored marks). pub stored: Option, } pub type Command = fn(&mut Cx, bool) -> bool; impl<'a> Cx<'a> { pub fn new(m: &'a Model, sel: Selection) -> Self { Self { m, sel, stored: None } } fn set_caret(&mut self, p: Pos) { self.sel = Selection::caret(p); self.stored = None; } /// The caret's block and offset when the selection is a collapsed caret in text. fn caret(&self) -> Option<(Blk, Pos)> { let p = self.sel.cursor()?; let b = self.m.at(p); b.kind().is_text().then_some((b, p)) } /// The block holding the selection head. pub fn head_block(&self) -> Option { self.sel.head().map(|h| self.m.at(h)) } } /// Runs the first command that applies. pub fn chain(cx: &mut Cx, cmds: &[Command], apply: bool) -> bool { cmds.iter().any(|c| c(cx, apply)) } // --------------------------------------------------------------------------- // Structure // --------------------------------------------------------------------------- fn common(a: &[Wrap], b: &[Wrap]) -> usize { a.iter().zip(b).take_while(|(x, y)| x == y).count() } /// Levels `cur` shares with `prev`: whole containers, and at a list level the item. pub fn keep(prev: Option<&Attrs>, cur: &Attrs) -> usize { let Some(p) = prev else { return 0 }; cur.join.unwrap_or_else(|| default_join(&p.wrap, &cur.wrap)).min(common(&p.wrap, &cur.wrap)) } /// The `join` that gives a block with `wrap` keep `k` after `prev`. fn join_for(prev: Option<&Attrs>, wrap: &[Wrap], k: usize) -> Option { let p = prev?; let k = k.min(common(&p.wrap, wrap)); (k != default_join(&p.wrap, wrap)).then_some(k) } fn prev_of(m: &Model, b: &Blk) -> Option { b.index.checked_sub(1).and_then(|i| m.block(i)) } fn keep_of(m: &Model, b: &Blk) -> usize { keep(prev_of(m, b).as_ref().map(|p| &p.attrs), &b.attrs) } /// The keep of the block after `b`, if any. fn next_keep(m: &Model, b: &Blk) -> Option { m.block(b.index + 1).map(|n| keep(Some(&b.attrs), &n.attrs)) } /// Rewrites blocks `lo..`: each entry's attributes, its join from the wanted keep /// (None: as given). Then gives the following block keep `next` (its old keep). fn relink(m: &Model, lo: usize, new: Vec<(Attrs, Option)>, next: Option) { let mut prev = lo.checked_sub(1).and_then(|i| m.block(i)).map(|b| b.attrs); let mut out = Vec::with_capacity(new.len() + 1); for (mut a, k) in new { if let Some(k) = k { a.join = join_for(prev.as_ref(), &a.wrap, k); } prev = Some(a.clone()); out.push(Some(a)); } if let (Some(k), Some(b)) = (next, m.block(lo + out.len())) { let mut a = b.attrs.clone(); a.join = join_for(prev.as_ref(), &a.wrap, k); out.push(Some(a)); } m.set_attrs(lo, &out); } /// Whether `cur` stays in the level-`d` node of `prev`: the same item, or with `list` /// the same list. fn same_node(prev: &Attrs, cur: &Attrs, d: usize, list: bool) -> bool { let k = keep(Some(prev), cur); k > d || (list && k == d && common(&prev.wrap, &cur.wrap) > d && cur.wrap[d].is_list()) } /// Blocks `(first, last)` in the level-`d` node holding block `i`. fn extent(m: &Model, i: usize, d: usize, list: bool) -> (usize, usize) { let cur = m.block(i).expect("block").attrs; let (mut s, mut e) = (i, i); let mut c = cur.clone(); m.scan(i, true, |info, a| { if same_node(a, &c, d, list) { s = info.index; c = a.clone(); true } else { false } }); let mut p = cur; m.scan(i + 1, false, |info, a| { if same_node(&p, a, d, list) { e = info.index; p = a.clone(); true } else { false } }); (s, e) } /// Blocks `lo..=hi` with their old keeps. fn with_keeps(m: &Model, lo: usize, hi: usize) -> Vec<(Blk, usize)> { let blocks = m.blocks(lo, hi + 1); let mut prev = lo.checked_sub(1).and_then(|i| m.block(i)).map(|b| b.attrs); blocks .into_iter() .map(|b| { let k = keep(prev.as_ref(), &b.attrs); prev = Some(b.attrs.clone()); (b, k) }) .collect() } /// Deletes block `b` whole; the next block keeps what both shared with the one before. fn remove_block(m: &Model, b: &Blk) { if m.len() == 1 { m.delete(b.start, b.sep); m.set_attrs(0, &[Some(Attrs::default())]); return; } let kb = keep_of(m, b); let kn = next_keep(m, b); m.delete(b.start, b.end()); if let Some(kn) = kn { relink(m, b.index, Vec::new(), Some(kn.min(kb))); } } /// Inserts a block of `attrs` after `b`, keeping `k` levels with it. Returns its start. fn block_after(m: &Model, b: &Blk, mut attrs: Attrs, k: usize) -> Pos { let nk = next_keep(m, b); attrs.join = join_for(Some(&b.attrs), &attrs.wrap, k); m.insert_blocks(b.end(), &[FlatBlock { attrs, ..Default::default() }]); if let Some(nk) = nk { relink(m, b.index + 2, Vec::new(), Some(nk)); } b.end() } /// Inserts a block of `attrs` before `b`, taking `b`'s place; `b` then shares all its /// levels with it. Returns the new block's start. fn block_before(m: &Model, b: &Blk, mut attrs: Attrs) -> Pos { let kb = keep_of(m, b); attrs.join = None; m.insert_blocks(b.start, &[FlatBlock { attrs: attrs.clone(), ..Default::default() }]); let d = b.depth(); relink(m, b.index, vec![(attrs, Some(kb)), (b.attrs.clone(), Some(d))], None); b.start } /// A paragraph in the containers of `b`. fn para_in(b: &Blk) -> Attrs { Attrs { wrap: b.attrs.wrap.clone(), ..Attrs::default() } } /// Clears inline marks and drops images from `from..to` (text becoming code). fn to_plain(m: &Model, from: Pos, to: Pos) { if from >= to { return; } let (a, b) = (m.to_u(from), m.to_u(to)); m.restyle(INLINE.iter().map(|k| Seg { from: a, to: b, key: k, value: None }).collect()); let text: Vec = m.plain(from, to).encode_utf16().collect(); for (i, _) in text.iter().enumerate().rev().filter(|(_, c)| **c == flat::OBJ as u16) { m.delete(from + i, from + i + 1); } } // --------------------------------------------------------------------------- // Marks at a position // --------------------------------------------------------------------------- /// Marks of the first run of `from..to`; a break or image carries none. fn run_marks(m: &Model, from: Pos, to: Pos, last: bool) -> Option { let runs = m.slice(from, to); let run = if last { runs.into_iter().last() } else { runs.into_iter().next() }; let TextDelta::Insert { insert, attributes } = run? else { return None }; let c = if last { insert.chars().last()? } else { insert.chars().next()? }; if c == '\n' || c == flat::OBJ || c == flat::SEP { return Some(Marks::none()); } Some(Marks::from_attrs(attributes.as_ref())) } /// PM `ResolvedPos.marks()`: inside a run its marks; at a boundary the marks of the /// run before (after, at the block start), minus a link that does not continue on the /// other side. pub fn marks_at(m: &Model, off: Pos) -> Marks { let b = m.at(off); if b.is_empty() || b.kind() != Leaf::Para && !matches!(b.kind(), Leaf::Heading(_)) { return Marks::none(); } let before = (off > b.start).then(|| run_marks(m, off.saturating_sub(2).max(b.start), off, true)).flatten(); let after = (off < b.sep).then(|| run_marks(m, off, (off + 2).min(b.sep), false)).flatten(); let (main, other) = match (before, after) { (Some(x), a) => (x, a), (None, Some(a)) => (a, None), (None, None) => return Marks::none(), }; let mut mk = main; if mk.link.is_some() && other.is_none_or(|o| o.link != mk.link) { mk.link = None; } mk } /// Marks the next inserted text gets. pub fn pending_marks(cx: &Cx) -> Marks { if let Some(m) = &cx.stored { return m.clone(); } match cx.sel.cursor() { Some(p) => marks_at(cx.m, p), None => Marks::none(), } } // --------------------------------------------------------------------------- // Text input // --------------------------------------------------------------------------- /// Replaces the selection with `text` carrying the pending marks. pub fn insert_text(cx: &mut Cx, text: &str) -> bool { let marks = if cx.sel.is_empty() { pending_marks(cx) } else { // Typing over a range takes the marks at its start (PM uses $from.marks()). pos::text_range(cx.m, &cx.sel).map_or(Marks::none(), |(from, _)| { let b = cx.m.at(from); if from < b.sep { run_marks(cx.m, from, (from + 2).min(b.sep), false).unwrap_or_default() } else { marks_at(cx.m, from) } }) }; if !cx.sel.is_empty() && !delete_selection(cx, true) { return false; } let Some((b, off)) = cx.caret() else { return false }; let marks = if b.kind() == Leaf::Code { Marks::none() } else { marks }; let end = cx.m.insert(off, text, &marks); cx.set_caret(end); true } /// Inserts inline content (paste) at the selection. pub fn insert_inline(cx: &mut Cx, inl: &[Inline]) -> bool { if !cx.sel.is_empty() && !delete_selection(cx, true) { return false; } let Some((b, off)) = cx.caret() else { return false }; let end = if b.kind() == Leaf::Code { cx.m.insert(off, &inline_text(inl), &Marks::none()) } else { cx.m.insert_inline(off, inl) }; cx.set_caret(end); true } fn inline_text(inl: &[Inline]) -> String { inl.iter() .map(|i| match i { Inline::Text(s, _) => s.as_str(), Inline::HardBreak => "\n", Inline::Image { .. } => "", }) .collect() } // --------------------------------------------------------------------------- // Deletion // --------------------------------------------------------------------------- pub fn delete_selection(cx: &mut Cx, apply: bool) -> bool { match cx.sel { Selection::Text { anchor, head } if anchor != head => { if apply { let (from, to) = (anchor.min(head), anchor.max(head)); delete_range(cx.m, from, to); cx.set_caret(from); } true } Selection::All => { if apply { let last = cx.m.last(); cx.m.delete(0, last.sep); cx.m.set_attrs(0, &[Some(Attrs::default())]); cx.set_caret(0); } true } Selection::Node(p) => { let b = cx.m.at(p); if apply { if b.kind() == Leaf::Rule { remove_block(cx.m, &b); let near = pos::snap(cx.m, b.start.min(cx.m.last().sep)); cx.set_caret(near); } else { // An image inside a text block: one char. cx.m.delete(p, p + 1); cx.set_caret(p); } } true } _ => false, } } /// Deletes `from..to`. Across blocks the merged block keeps the first block's /// attributes, and the block after the range keeps the levels it shared with the last /// one where those match the first one's. pub fn delete_range(m: &Model, from: Pos, to: Pos) { let x = m.at(from); let y = m.at(to); if x.index == y.index { m.delete(from, to); return; } let kz = next_keep(m, &y); let cw = common(&x.attrs.wrap, &y.attrs.wrap); let tail = y.sep - to; m.delete(from, to); if x.kind() == Leaf::Code && y.kind() != Leaf::Code { to_plain(m, from, from + tail); } relink(m, x.index, vec![(x.attrs.clone(), None)], kz.map(|k| k.min(cw))); } /// Merges block `b` into the block `a` before it (same containers). Returns the join point. fn join_into(m: &Model, a: &Blk, b: &Blk) -> Pos { m.delete(a.sep, a.sep + 1); m.set_attrs(a.index, &[Some(a.attrs.clone())]); if a.kind() == Leaf::Code && b.kind() != Leaf::Code { to_plain(m, a.sep, a.sep + b.len()); } a.sep } pub fn join_backward(cx: &mut Cx, apply: bool) -> bool { let Some((b, off)) = cx.caret() else { return false }; if off != b.start { return false; } let m = cx.m; let Some(a) = prev_of(m, &b) else { return lift(cx, &b, apply) }; let k = keep(Some(&a.attrs), &b.attrs); let l = b.depth(); if k < l { // First in a container: join the previous one of its kind, else leave it. if common(&a.attrs.wrap, &b.attrs.wrap) > k { if apply { let nk = next_keep(m, &b); relink(m, b.index, vec![(b.attrs.clone(), Some(k + 1))], nk); } return true; } return lift(cx, &b, apply); } if a.depth() > l { // After a container: move into its trailing item or quote. let mut n = l + 1; while n < a.depth() && a.attrs.wrap[n] == Wrap::Quote { n += 1; } if apply { let nk = next_keep(m, &b); let mut at = b.attrs.clone(); at.wrap = a.attrs.wrap[..n].to_vec(); relink(m, b.index, vec![(at, Some(n))], nk); } return true; } if !apply { return true; } if a.kind() == Leaf::Rule { if b.is_empty() { remove_block(m, &b); cx.sel = Selection::Node(a.start); } else { remove_block(m, &a); cx.set_caret(a.start); } } else if a.is_empty() { remove_block(m, &a); cx.set_caret(a.start); } else { let at = join_into(m, &a, &b); cx.set_caret(at); } true } pub fn join_forward(cx: &mut Cx, apply: bool) -> bool { let Some((b, off)) = cx.caret() else { return false }; if off != b.sep { return false; } let m = cx.m; let Some(c) = m.block(b.index + 1) else { return false }; let k = keep(Some(&b.attrs), &c.attrs); let l = c.depth(); if b.is_empty() { if apply { remove_block(m, &b); cx.sel = if c.kind() == Leaf::Rule { Selection::Node(b.start) } else { Selection::caret(b.start) }; } return true; } if k < l { if common(&b.attrs.wrap, &c.attrs.wrap) > k { if apply { let nk = next_keep(m, &c); relink(m, c.index, vec![(c.attrs.clone(), Some(k + 1))], nk); } return true; } let sel = cx.sel.clone(); let ran = lift(cx, &c, apply); cx.sel = sel; return ran; } if b.depth() > l { return false; } if apply { if c.kind() == Leaf::Rule { remove_block(m, &c); } else { join_into(m, &b, &c); } cx.set_caret(b.sep); } true } pub fn select_node_backward(cx: &mut Cx, apply: bool) -> bool { let Some((b, off)) = cx.caret() else { return false }; if off != b.start { return false; } match prev_of(cx.m, &b) { Some(a) if a.kind() == Leaf::Rule => { if apply { cx.sel = Selection::Node(a.start); } true } _ => false, } } pub fn select_node_forward(cx: &mut Cx, apply: bool) -> bool { let Some((b, off)) = cx.caret() else { return false }; if off != b.sep { return false; } match cx.m.block(b.index + 1) { Some(c) if c.kind() == Leaf::Rule => { if apply { cx.sel = Selection::Node(c.start); } true } _ => false, } } // --------------------------------------------------------------------------- // Enter // --------------------------------------------------------------------------- pub fn newline_in_code(cx: &mut Cx, apply: bool) -> bool { let Some(b) = cx.head_block() else { return false }; if b.kind() != Leaf::Code { return false; } if let Selection::Text { anchor, .. } = cx.sel && !b.holds(anchor) { return false; } !apply || insert_text(cx, "\n") } pub fn create_paragraph_near(cx: &mut Cx, apply: bool) -> bool { let m = cx.m; match cx.sel { Selection::Node(p) => { let b = m.at(p); if b.kind() != Leaf::Rule { return false; } if apply { let at = if b.index == 0 { block_before(m, &b, para_in(&b)) } else { block_after(m, &b, para_in(&b), b.depth()) }; cx.set_caret(at); } true } Selection::Gap(p) => { if apply { let at = if p < m.total() { let b = m.at(p); let mut a = para_in(&b); a.start = b.attrs.start; block_before(m, &b, a) } else { let b = m.last(); block_after(m, &b, para_in(&b), b.depth()) }; cx.set_caret(at); } true } _ => false, } } pub fn lift_empty_block(cx: &mut Cx, apply: bool) -> bool { let Some((b, _)) = cx.caret() else { return false }; if !b.is_empty() || b.depth() == 0 { return false; } lift(cx, &b, apply) } pub fn split_block(cx: &mut Cx, apply: bool) -> bool { if !matches!(cx.sel, Selection::Text { .. }) { return false; } if !apply { return true; } if !cx.sel.is_empty() { delete_selection(cx, true); } let Some((b, off)) = cx.caret() else { return false }; let at_end = off == b.sep; let mut first = b.attrs.clone(); if off == b.start && !at_end && b.kind() != Leaf::Para { // Enter at the start of a heading: the empty first half is a paragraph. first.kind = Leaf::Para; first.lang = None; } let tail = Attrs { kind: if at_end { Leaf::Para } else { b.kind() }, lang: if at_end { None } else { b.attrs.lang.clone() }, wrap: b.attrs.wrap.clone(), join: None, start: None, }; let m = cx.m; m.insert_blocks(off, &[FlatBlock { attrs: first, ..Default::default() }]); relink(m, b.index + 1, vec![(tail, Some(b.depth()))], None); cx.set_caret(off + 1); true } pub fn exit_code(cx: &mut Cx, apply: bool) -> bool { let Some(b) = cx.head_block() else { return false }; if b.kind() != Leaf::Code { return false; } if apply { let at = block_after(cx.m, &b, para_in(&b), b.depth()); cx.set_caret(at); } true } pub fn select_all(cx: &mut Cx, apply: bool) -> bool { if apply { cx.sel = Selection::All; } true } // --------------------------------------------------------------------------- // Lists and quotes // --------------------------------------------------------------------------- /// Moves block `b` out of its innermost container: its list item, or its quote. fn lift(cx: &mut Cx, b: &Blk, apply: bool) -> bool { let l = b.depth(); if l == 0 { return false; } let d = l - 1; if b.attrs.wrap[d].is_list() { return lift_item(cx.m, b.index, d, apply); } if apply { pop_level(cx.m, b, d); } true } /// Removes the innermost level `d` of a single block; what followed in that /// container opens a new one after it. fn pop_level(m: &Model, b: &Blk, d: usize) { let kb = keep_of(m, b); let kn = next_keep(m, b); let mut a = b.attrs.clone(); a.wrap.truncate(d); relink(m, b.index, vec![(a, Some(kb.min(d)))], kn.map(|k| k.min(d))); } /// liftListItem for the item at level `d` holding block `i`: the item leaves that /// list. Nested, it becomes an item of the outer list and the items after it a list /// inside it; at the top its blocks replace it and the list continues after them. fn lift_item(m: &Model, i: usize, d: usize, apply: bool) -> bool { if !apply { return true; } let (s, e) = extent(m, i, d, false); let blocks = with_keeps(m, s, e); let first = &blocks[0].0; let nested = d > 0 && first.attrs.wrap[d - 1].is_list(); let next = m.block(e + 1); let next_is_item = next.as_ref().is_some_and(|n| same_node(&blocks.last().unwrap().0.attrs, &n.attrs, d, true)); let nk = next.as_ref().map(|n| if next_is_item { d } else { keep(Some(&blocks.last().unwrap().0.attrs), &n.attrs) }); let new = blocks .iter() .enumerate() .map(|(j, (b, k))| { let mut a = b.attrs.clone(); a.wrap.remove(d); let k = if j == 0 { (*k).min(if nested { d - 1 } else { d }) } else { k - 1 }; if j == 0 { a.start = None; } (a, Some(k)) }) .collect(); relink(m, s, new, nk); true } /// The innermost list level of block `b` that it sits in directly. fn item_level(b: &Blk) -> Option { let d = b.depth().checked_sub(1)?; b.attrs.wrap[d].is_list().then_some(d) } pub fn split_list_item(cx: &mut Cx, apply: bool) -> bool { let Some(b) = cx.head_block() else { return false }; if !matches!(cx.sel, Selection::Text { .. }) || !b.kind().is_text() { return false; } let Some(d) = item_level(&b) else { return false }; let m = cx.m; let kb = keep_of(m, &b); let last_in_item = m.block(b.index + 1).is_none_or(|n| keep(Some(&b.attrs), &n.attrs) <= d); if b.is_empty() && last_in_item && cx.sel.is_empty() { if kb <= d { // An empty item: Enter leaves the list. return lift_item(m, b.index, d, apply); } // An empty last paragraph of an item becomes the next item. if apply { let nk = next_keep(m, &b); relink(m, b.index, vec![(b.attrs.clone(), Some(d))], nk); } return true; } if !apply { return true; } if !cx.sel.is_empty() { delete_selection(cx, true); } let Some((b, off)) = cx.caret() else { return false }; let tail = Attrs { wrap: b.attrs.wrap.clone(), ..Attrs::default() }; m.insert_blocks(off, &[FlatBlock { attrs: b.attrs.clone(), ..Default::default() }]); relink(m, b.index + 1, vec![(tail, Some(d))], None); cx.set_caret(off + 1); true } pub fn sink_list_item(cx: &mut Cx, apply: bool) -> bool { let Some(b) = cx.head_block() else { return false }; let Some(d) = item_level(&b) else { return false }; let m = cx.m; let (s, e) = extent(m, b.index, d, false); let first = m.block(s).unwrap(); // Only an item with an item before it in the same list can sink. let Some(p) = prev_of(m, &first) else { return false }; if !same_node(&p.attrs, &first.attrs, d, true) { return false; } if !apply { return true; } let w = b.attrs.wrap[d]; let blocks = with_keeps(m, s, e); let nk = m.block(e + 1).map(|n| keep(Some(&blocks.last().unwrap().0.attrs), &n.attrs)); let new = blocks .iter() .enumerate() .map(|(j, (b, k))| { let mut a = b.attrs.clone(); a.wrap.insert(d + 1, w); (a, Some(if j == 0 { d + 1 } else { k + 1 })) }) .collect(); relink(m, s, new, nk); true } pub fn lift_list_item(cx: &mut Cx, apply: bool) -> bool { let Some(b) = cx.head_block() else { return false }; let Some(d) = b.attrs.wrap.iter().rposition(|w| w.is_list()) else { return false }; lift_item(cx.m, b.index, d, apply) } /// Wraps the blocks of the selection (whole nodes at their deepest common level) in a /// new list or quote. fn wrap_range(cx: &mut Cx, w: Wrap, apply: bool) -> bool { let m = cx.m; let Some((from, to)) = pos::text_range(m, &cx.sel) else { return false }; let (x, y) = (m.at(from), m.at(to)); let range = with_keeps(m, x.index, y.index); if range.is_empty() { return false; } let mut d = x.depth(); for (b, k) in &range[1..] { d = d.min(*k).min(b.depth()); } let (s, _) = if x.index == 0 || keep_of(m, &x) <= d { (x.index, 0) } else { extent(m, x.index, d, false) }; let (_, e) = if y.depth() <= d { (0, y.index) } else { extent(m, y.index, d, false) }; let blocks = with_keeps(m, s, e); let first = &blocks[0]; // The first block of a list item stays its first block. if d > 0 && first.0.attrs.wrap[d - 1].is_list() && first.1 < d { return false; } if w.is_list() { let mut prev = &blocks[0].0; for (b, k) in &blocks[1..] { if *k == d && same_node(&prev.attrs, &b.attrs, d, true) && b.depth() > d { return false; } prev = b; } } if !apply { return true; } let nk = m.block(e + 1).map(|n| keep(Some(&blocks.last().unwrap().0.attrs), &n.attrs)); let new = blocks .iter() .enumerate() .map(|(j, (b, k))| { let mut a = b.attrs.clone(); a.wrap.insert(d, w); let k = match j { 0 => *k, _ if w.is_list() && *k == d => d, _ => k + 1, }; (a, Some(k)) }) .collect(); relink(m, s, new, nk); true } pub fn wrap_in_list(cx: &mut Cx, kind: Kind, start: Option, apply: bool) -> bool { let Some(w) = kind.wrap().filter(|w| w.is_list()) else { return false }; let ran = wrap_range(cx, w, apply); if ran && apply && let Some(n) = start.filter(|&n| n != 1) && let Some((from, _)) = pos::text_range(cx.m, &cx.sel) { let b = cx.m.at(from); let mut a = b.attrs.clone(); a.start = Some(n); cx.m.set_attrs(b.index, &[Some(a)]); } ran } pub fn wrap_in(cx: &mut Cx, kind: Kind, apply: bool) -> bool { match kind.wrap() { Some(w) => wrap_range(cx, w, apply), None => false, } } /// Changes the type of the list at level `d` holding block `i`. fn retype_list(m: &Model, i: usize, d: usize, w: Wrap) { let (s, e) = extent(m, i, d, true); let blocks = with_keeps(m, s, e); let nk = m.block(e + 1).map(|n| keep(Some(&blocks.last().unwrap().0.attrs), &n.attrs)); let new = blocks .into_iter() .map(|(b, k)| { let mut a = b.attrs; a.wrap[d] = w; (a, Some(k)) }) .collect(); relink(m, s, new, nk); } /// The innermost container of the head block matching `pred`. pub fn ancestor_kind(cx: &Cx, pred: fn(Kind) -> bool) -> Option { let b = cx.head_block()?; b.attrs.wrap.iter().rev().map(|w| Kind::of_wrap(*w)).find(|k| pred(*k)) } pub fn toggle_list(cx: &mut Cx, kind: Kind, apply: bool) -> bool { let Some(w) = kind.wrap() else { return false }; let Some(b) = cx.head_block() else { return false }; match b.attrs.wrap.iter().rposition(|x| x.is_list()) { None => wrap_range(cx, w, apply), Some(d) if b.attrs.wrap[d] == w => lift_item(cx.m, b.index, d, apply), Some(d) => { if apply { retype_list(cx.m, b.index, d, w); } true } } } pub fn toggle_quote(cx: &mut Cx, apply: bool) -> bool { let Some(b) = cx.head_block() else { return false }; let Some(q) = b.attrs.wrap.iter().rposition(|w| *w == Wrap::Quote) else { return wrap_range(cx, Wrap::Quote, apply) }; if !apply { return true; } // The quote's child holding the block leaves it; the quote splits around it. let m = cx.m; let (s, e) = if b.depth() > q + 1 { extent(m, b.index, q + 1, true) } else { (b.index, b.index) }; let blocks = with_keeps(m, s, e); let nk = m.block(e + 1).map(|n| keep(Some(&blocks.last().unwrap().0.attrs), &n.attrs).min(q)); let new = blocks .iter() .enumerate() .map(|(j, (b, k))| { let mut a = b.attrs.clone(); a.wrap.remove(q); (a, Some(if j == 0 { (*k).min(q) } else { k - 1 })) }) .collect(); relink(m, s, new, nk); true } // --------------------------------------------------------------------------- // Block types // --------------------------------------------------------------------------- /// Text blocks from the one holding `from` through the one holding `to`. fn text_blocks(m: &Model, from: Pos, to: Pos) -> Vec { let (x, y) = (m.at(from), m.at(to)); m.blocks(x.index, y.index + 1).into_iter().filter(|b| b.kind().is_text()).collect() } /// Whether block `b` may become `kind`: the first block of a list item stays a paragraph. pub fn can_retype(m: &Model, b: &Blk, kind: Leaf) -> bool { match item_level(b) { Some(d) if keep_of(m, b) <= d => kind == Leaf::Para, _ => true, } } pub fn set_block_type(cx: &mut Cx, kind: Kind, apply: bool) -> bool { let Some(leaf) = kind.leaf() else { return false }; let m = cx.m; let Some((from, to)) = pos::text_range(m, &cx.sel) else { return false }; let (x, y) = (m.at(from), m.at(to)); if !apply { // A dry run (toolbar state) stops at the first block it could retype. let mut found = false; m.scan(x.index, false, |info, a| { if info.index > y.index { return false; } if a.kind.is_text() && a.kind != leaf { let b = m.block(info.index).unwrap(); found = can_retype(m, &b, leaf); } !found }); return found; } let blocks: Vec = text_blocks(m, from, to).into_iter().filter(|b| can_retype(m, b, leaf)).collect(); if !blocks.iter().any(|b| b.kind() != leaf) { return false; } if leaf == Leaf::Code { // Adjacent blocks in one container become one code block, a line each. let mut runs: Vec> = Vec::new(); for b in blocks { match runs.last_mut() { Some(r) if r.last().is_some_and(|p| p.index + 1 == b.index && p.attrs.wrap == b.attrs.wrap && keep(Some(&p.attrs), &b.attrs) == b.depth()) => r.push(b), _ => runs.push(vec![b]), } } for run in runs.iter().rev() { let (first, last) = (&run[0], run.last().unwrap()); to_plain(m, first.start, last.sep); let seps: Vec<(Pos, Option)> = (first.index..last.index).map(|i| (m.block(i).unwrap().sep, None)).collect(); m.swap_chars(seps); let mut a = first.attrs.clone(); a.kind = Leaf::Code; a.lang = None; m.set_attrs(first.index, &[Some(a)]); } } else { // A code block becomes one block per line. for b in blocks.iter().rev().filter(|b| b.kind() == Leaf::Code) { let text: Vec = m.plain(b.start, b.sep).encode_utf16().collect(); let breaks: Vec = text.iter().enumerate().filter(|(_, c)| **c == b'\n' as u16).map(|(i, _)| b.start + i).collect(); if breaks.is_empty() { continue; } let mut first = b.attrs.clone(); first.kind = leaf; first.lang = None; let rest = Attrs { kind: leaf, wrap: b.attrs.wrap.clone(), join: join_for(Some(&b.attrs), &b.attrs.wrap, b.depth()), ..Attrs::default() }; let mut swaps = vec![(breaks[0], Some(first))]; swaps.extend(breaks[1..].iter().map(|&p| (p, Some(rest.clone())))); m.swap_chars(swaps); let last = m.block(b.index + breaks.len()).unwrap(); m.set_attrs(last.index, &[Some(rest.clone())]); } let targets: Vec = text_blocks(m, from, to).into_iter().filter(|b| b.kind() != leaf && can_retype(m, b, leaf)).collect(); let mut changes: Vec<(usize, Attrs)> = Vec::new(); for b in targets { let mut a = b.attrs.clone(); a.kind = leaf; a.lang = None; changes.push((b.index, a)); } set_many(m, changes); } cx.sel = pos::clamp(m, &cx.sel); true } /// Sets attributes of scattered blocks (sorted), as few runs as possible. fn set_many(m: &Model, changes: Vec<(usize, Attrs)>) { let Some(lo) = changes.first().map(|c| c.0) else { return }; let hi = changes.last().unwrap().0; let mut new = vec![None; hi - lo + 1]; for (i, a) in changes { new[i - lo] = Some(a); } m.set_attrs(lo, &new); } pub fn is_block_active(cx: &Cx, kind: Kind) -> bool { cx.head_block().is_some_and(|b| Some(b.kind()) == kind.leaf()) } pub fn toggle_block(cx: &mut Cx, kind: Kind, apply: bool) -> bool { if is_block_active(cx, kind) { set_block_type(cx, Kind::Paragraph, apply) } else { set_block_type(cx, kind, apply) } } /// Sets the language of the code block holding `off` (None: detect). pub fn set_code_language(m: &Model, off: Pos, lang: Option<&str>) -> bool { let b = m.at(off); if b.kind() != Leaf::Code { return false; } let mut a = b.attrs.clone(); a.lang = lang.filter(|l| !l.is_empty()).map(str::to_owned); if a == b.attrs { return false; } m.set_attrs(b.index, &[Some(a)]); true } pub fn insert_rule(cx: &mut Cx, apply: bool) -> bool { let Some(b) = cx.head_block() else { return false }; if b.kind() == Leaf::Code || !b.kind().is_text() { return false; } if !apply { return true; } if !cx.sel.is_empty() { delete_selection(cx, true); } let Some((b, off)) = cx.caret() else { return false }; let m = cx.m; let rule = Attrs { kind: Leaf::Rule, wrap: b.attrs.wrap.clone(), ..Attrs::default() }; let l = b.depth(); if off == b.start { let at = block_before(m, &b, Attrs { start: b.attrs.start, ..rule }); cx.set_caret(at + 1); } else if off == b.sep { block_after(m, &b, rule, l); let r = m.block(b.index + 1).unwrap(); let next = m.block(r.index + 1).filter(|n| n.kind().is_text() && n.attrs.wrap == b.attrs.wrap && keep(Some(&r.attrs), &n.attrs) == l); let at = match next { Some(n) => n.start, None => block_after(m, &r, para_in(&b), l), }; cx.set_caret(at); } else { // Split, with the rule between the halves. let tail = Attrs { kind: b.kind(), lang: b.attrs.lang.clone(), wrap: b.attrs.wrap.clone(), ..Attrs::default() }; m.insert_blocks(off, &[FlatBlock { attrs: b.attrs.clone(), ..Default::default() }, FlatBlock { attrs: rule.clone(), ..Default::default() }]); relink(m, b.index + 1, vec![(rule, Some(l)), (tail, Some(l))], None); cx.set_caret(off + 2); } true } // --------------------------------------------------------------------------- // Inline marks // --------------------------------------------------------------------------- /// Content ranges of the non-code blocks in `from..to`, one per run of neighbours /// (a mark may cover the separators between them). fn mark_ranges(m: &Model, from: Pos, to: Pos) -> Vec<(Pos, Pos)> { let (x, y) = (m.at(from), m.at(to)); let mut out: Vec<(Pos, Pos)> = Vec::new(); let mut open = false; m.scan(x.index, false, |info, a| { if info.index > y.index { return false; } if a.kind == Leaf::Code { open = false; return true; } let (s, e) = (info.start16.max(from), info.sep16().min(to)); match out.last_mut() { Some(r) if open => r.1 = e, _ => out.push((s, e)), } open = true; true }); out.retain(|r| r.0 < r.1); out } /// Whether `from..to` holds text outside code blocks. fn has_markable(m: &Model, from: Pos, to: Pos) -> bool { let (x, y) = (m.at(from), m.at(to)); let mut found = false; m.scan(x.index, false, |info, a| { if info.index > y.index { return false; } found = a.kind != Leaf::Code && info.start16.max(from) < info.sep16().min(to); !found }); found } /// Whether mark `t` is on the stored marks (collapsed) or on any text of the /// selection, looking at most at `limit` UTF-16 units of it. pub fn mark_active_within(cx: &Cx, t: MarkType, limit: usize) -> bool { if cx.sel.is_empty() { return pending_marks(cx).has(t); } let Some((from, to)) = pos::text_range(cx.m, &cx.sel) else { return false }; let to = to.min(from.saturating_add(limit)); mark_ranges(cx.m, from, to).into_iter().any(|(a, b)| { cx.m.slice(a, b).into_iter().any(|d| match d { TextDelta::Insert { insert, attributes } => { Marks::from_attrs(attributes.as_ref()).has(t) && insert.chars().any(|c| c != flat::SEP) } _ => false, }) }) } /// Units of the selection the toolbar looks at for mark state. pub const MARK_STATE_UNITS: usize = 1 << 16; pub fn is_mark_active(cx: &Cx, t: MarkType) -> bool { mark_active_within(cx, t, usize::MAX) } fn is_space(c: u16) -> bool { c == b' ' as u16 || c == b'\t' as u16 || c == b'\n' as u16 || c == 0xa0 || c == flat::SEP as u16 } /// `(a, b)` without surrounding whitespace, reading only near the ends. fn trim(m: &Model, mut a: Pos, mut b: Pos) -> (Pos, Pos) { while a < b { let n = (b - a).min(256); let s: Vec = m.plain(a, a + n).encode_utf16().collect(); let k = s.iter().take_while(|c| is_space(**c)).count(); a += k; if k < n { break; } } while b > a { let n = (b - a).min(256); let s: Vec = m.plain(b - n, b).encode_utf16().collect(); let k = s.iter().rev().take_while(|c| is_space(**c)).count(); b -= k; if k < n { break; } } (a, b) } fn mark_value(t: MarkType, link: Option) -> Option { let mut mk = Marks::none(); match t { MarkType::Link => mk.link = link, t => mk.set(t, true), } mk.value_of(t.key()) } /// Adds mark `t` over the text of `from..to` (input rules). pub fn add_mark(m: &Model, from: Pos, to: Pos, t: MarkType) { style(m, mark_ranges(m, from, to), t, mark_value(t, None)); } fn style(m: &Model, ranges: Vec<(Pos, Pos)>, t: MarkType, value: Option) { let segs = ranges .into_iter() .filter(|r| r.0 < r.1) .map(|(a, b)| Seg { from: m.to_u(a), to: m.to_u(b), key: t.key(), value: value.clone() }) .collect(); m.restyle(segs); } pub fn toggle_mark(cx: &mut Cx, t: MarkType, apply: bool) -> bool { if cx.sel.is_empty() { let Some(b) = cx.head_block() else { return false }; if b.kind() == Leaf::Code { return false; } if apply { let mut mk = pending_marks(cx); let on = !mk.has(t); mk.set(t, on); cx.stored = Some(mk); } return true; } let Some((from, to)) = pos::text_range(cx.m, &cx.sel) else { return false }; if !apply { return has_markable(cx.m, from, to); } let ranges = mark_ranges(cx.m, from, to); if ranges.is_empty() { return false; } let remove = is_mark_active(cx, t); let ranges = if remove { ranges } else { ranges.into_iter().map(|(a, b)| trim(cx.m, a, b)).collect() }; style(cx.m, ranges, t, if remove { None } else { mark_value(t, None) }); true } /// Sets or clears the link over `from..to`. pub fn set_link(cx: &mut Cx, from: Pos, to: Pos, href: Option<&str>) { let link = href.map(|h| Link { href: h.to_owned(), title: None }); let value = link.is_some().then(|| mark_value(MarkType::Link, link)).flatten(); style(cx.m, mark_ranges(cx.m, from, to), MarkType::Link, value); } /// The link around `off`, within its block: `(from, to, link)`. pub fn link_range_at(m: &Model, off: Pos) -> Option<(Pos, Pos, Link)> { let b = m.at(off); if b.kind() == Leaf::Code || b.is_empty() { return None; } // Most carets touch no link: check the neighbouring units before reading further. let near = m.slice(off.saturating_sub(1).max(b.start), (off + 1).min(b.sep)); let link = near.iter().find_map(|d| match d { TextDelta::Insert { attributes, .. } => Marks::from_attrs(attributes.as_ref()).link, _ => None, })?; let mut pos = b.start; let mut found: Option<(Pos, Pos)> = None; for d in m.slice(b.start, b.sep) { let TextDelta::Insert { insert, attributes } = d else { continue }; let len = insert.encode_utf16().count(); if Marks::from_attrs(attributes.as_ref()).link.as_ref() == Some(&link) { found = match found { Some((a, e)) if e == pos => Some((a, pos + len)), Some(r) if r.1 >= off => break, _ => Some((pos, pos + len)), }; } else if found.is_some_and(|r| r.1 >= off) { break; } pos += len; } found.filter(|r| r.0 <= off && off <= r.1).map(|(a, e)| (a, e, link)) } /// Whether the link popover may open: a text selection in non-code text, or a caret /// inside a link (the TS `toggleLink`). pub fn can_link(cx: &Cx) -> bool { if let Some(p) = cx.sel.cursor() { return link_range_at(cx.m, p).is_some(); } match pos::text_range(cx.m, &cx.sel) { Some((from, to)) if from < to => has_markable(cx.m, from, to), _ => false, } } // --------------------------------------------------------------------------- // Paste and copy // --------------------------------------------------------------------------- fn block_lines(b: &Block, out: &mut Vec) { match b { Block::Paragraph(v) | Block::Heading(_, v) => out.push(inline_text(v)), Block::Code { text, .. } => out.push(text.clone()), Block::Quote(bs) => bs.iter().for_each(|b| block_lines(b, out)), Block::List { items, .. } => items.iter().flatten().for_each(|b| block_lines(b, out)), Block::Rule => {} } } /// Replaces the selection with pasted blocks, like PM's `replaceSelection`: the first /// block's text joins the caret's block, the rest follow inside the caret block's /// containers, and the text after the caret joins the last pasted block. pub fn insert_blocks(cx: &mut Cx, blocks: &[Block]) -> bool { if blocks.is_empty() { return false; } if !cx.sel.is_empty() && !delete_selection(cx, true) { return false; } let Some((b, off)) = cx.caret() else { return false }; if b.kind() == Leaf::Code { let mut lines = Vec::new(); blocks.iter().for_each(|x| block_lines(x, &mut lines)); return insert_text(cx, &lines.join("\n")); } let m = cx.m; let mut flat = flat::flatten(blocks); let inline = |f: &FlatBlock| f.attrs.wrap.is_empty() && matches!(f.attrs.kind, Leaf::Para | Leaf::Heading(_)); if flat.len() == 1 && inline(&flat[0]) { return insert_inline(cx, &flat[0].inl); } // Keeps inside the paste, then shifted under the caret block's containers. let l = b.depth(); let mut keeps = Vec::with_capacity(flat.len()); let mut prev: Option = None; for f in &flat { keeps.push(keep(prev.as_ref(), &f.attrs) + l); prev = Some(f.attrs.clone()); } for f in &mut flat { let mut w = b.attrs.wrap.clone(); w.extend_from_slice(&f.attrs.wrap); f.attrs.wrap = w; f.attrs.join = None; } let head_inline = inline(&flat[0]); let head_empty = off == b.start && !head_inline; let tail_empty = off == b.sep; let n = flat.len(); let merge_last = (n > 1 || !head_inline) && (inline(&flat[n - 1]) || tail_empty); let nk = next_keep(m, &b); let kb = keep_of(m, &b); let mut at = off; if head_inline { at = m.insert_inline(at, &flat[0].inl); } let lo = if head_inline { 1 } else { 0 }; let hi = if merge_last { n - 1 } else { n }; let mut written: Vec = Vec::new(); // (attrs, keep) of each block from the caret block on, for relink. let mut entries: Vec<(Attrs, Option)> = Vec::new(); if !head_empty { written.push(FlatBlock { attrs: b.attrs.clone(), ..Default::default() }); entries.push((b.attrs.clone(), None)); } for (j, f) in flat.iter().enumerate().take(hi).skip(lo) { written.push(f.clone()); let k = if j == 0 { if head_empty { kb } else { l } } else { keeps[j] }; entries.push((f.attrs.clone(), Some(k))); } at = m.insert_blocks(at, &written); let tail_attrs = if merge_last { let f = &flat[n - 1]; if f.attrs.kind == Leaf::Code { at = m.insert(at, &f.plain(), &Marks::none()); } else { at = m.insert_inline(at, &f.inl); } let k = if n == 1 && head_empty { kb } else { keeps[n - 1] }; (f.attrs.clone(), Some(k)) } else { (Attrs { kind: b.kind(), lang: b.attrs.lang.clone(), wrap: b.attrs.wrap.clone(), ..Attrs::default() }, Some(l)) }; entries.push(tail_attrs); relink(m, b.index, entries, nk); cx.set_caret(pos::snap(m, at)); true } /// The selected content as blocks. A selection inside one block gives one paragraph /// (pasting it back merges into the target block). pub fn selected_blocks(m: &Model, sel: &Selection) -> Vec { if let Selection::Node(p) = *sel { let b = m.at(p); if b.kind() == Leaf::Rule { return vec![Block::Rule]; } let fb = flat::read_delta(m.slice(p, p + 1)); return vec![Block::Paragraph(fb.into_iter().next().map(|f| f.inl).unwrap_or_default())]; } let Some((from, to)) = pos::text_range(m, sel) else { return Vec::new() }; let (x, y) = (m.at(from), m.at(to)); if x.index == y.index { let fb = flat::read_delta(m.slice(from, to)); let inl = fb.into_iter().next().map(|mut f| { if x.kind() == Leaf::Code { vec![Inline::Text(f.plain(), Default::default())] } else { std::mem::take(&mut f.inl) } }); return vec![Block::Paragraph(inl.unwrap_or_default())]; } let mut blocks = flat::read_delta(m.slice(from, to)); if to > y.start && let Some(last) = blocks.last_mut() { last.attrs = y.attrs.clone(); if last.attrs.kind == Leaf::Code { let t = last.plain(); last.inl = vec![Inline::Text(t, Default::default())]; } } flat::nest(&blocks) }