forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

commands.rs1390 lines, 47.0 KiBHistoryRawDownload
1//! Editing commands over the flat body ([`note_model::flat`]): the keymap semantics of
2//! prosemirror-commands / prosemirror-schema-list and the app's toggles, as edits of
3//! text, separators and the wrap paths separators carry.
4//!
5//! Structure is relative: a block shares [`keep`] levels with the block before it
6//! (whole containers, and for a list the item), then opens the rest. Commands change
7//! wraps and keeps of a block range and restore the keep of the block after it, so
8//! nothing outside the range moves.
9//!
10//! A command takes the context and `apply`. With `apply == false` it only reports
11//! whether it would do something and must not edit (toolbar state). With `apply` it
12//! edits through the model's primitives and sets `cx.sel`.
13
14use note_model::flat::{self, Attrs, FlatBlock, Kind as Leaf, Wrap, default_join};
15use note_model::write::{Block, Inline};
16
17use loro::{LoroValue, TextDelta};
18
19use super::doc::Kind;
20use super::marks::{Link, MarkType, Marks};
21use super::model::{Blk, INLINE, Model, Seg};
22use super::pos::{self, Pos, Selection};
23
24pub struct Cx<'a> {
25 pub m: &'a Model,
26 pub sel: Selection,
27 /// Marks for the next typed text at a collapsed cursor (PM stored marks).
28 pub stored: Option<Marks>,
29}
30
31pub type Command = fn(&mut Cx, bool) -> bool;
32
33impl<'a> Cx<'a> {
34 pub fn new(m: &'a Model, sel: Selection) -> Self {
35 Self { m, sel, stored: None }
36 }
37
38 fn set_caret(&mut self, p: Pos) {
39 self.sel = Selection::caret(p);
40 self.stored = None;
41 }
42
43 /// The caret's block and offset when the selection is a collapsed caret in text.
44 fn caret(&self) -> Option<(Blk, Pos)> {
45 let p = self.sel.cursor()?;
46 let b = self.m.at(p);
47 b.kind().is_text().then_some((b, p))
48 }
49
50 /// The block holding the selection head.
51 pub fn head_block(&self) -> Option<Blk> {
52 self.sel.head().map(|h| self.m.at(h))
53 }
54}
55
56/// Runs the first command that applies.
57pub fn chain(cx: &mut Cx, cmds: &[Command], apply: bool) -> bool {
58 cmds.iter().any(|c| c(cx, apply))
59}
60
61// ---------------------------------------------------------------------------
62// Structure
63// ---------------------------------------------------------------------------
64
65fn common(a: &[Wrap], b: &[Wrap]) -> usize {
66 a.iter().zip(b).take_while(|(x, y)| x == y).count()
67}
68
69/// Levels `cur` shares with `prev`: whole containers, and at a list level the item.
70pub fn keep(prev: Option<&Attrs>, cur: &Attrs) -> usize {
71 let Some(p) = prev else { return 0 };
72 cur.join.unwrap_or_else(|| default_join(&p.wrap, &cur.wrap)).min(common(&p.wrap, &cur.wrap))
73}
74
75/// The `join` that gives a block with `wrap` keep `k` after `prev`.
76fn join_for(prev: Option<&Attrs>, wrap: &[Wrap], k: usize) -> Option<usize> {
77 let p = prev?;
78 let k = k.min(common(&p.wrap, wrap));
79 (k != default_join(&p.wrap, wrap)).then_some(k)
80}
81
82fn prev_of(m: &Model, b: &Blk) -> Option<Blk> {
83 b.index.checked_sub(1).and_then(|i| m.block(i))
84}
85
86fn keep_of(m: &Model, b: &Blk) -> usize {
87 keep(prev_of(m, b).as_ref().map(|p| &p.attrs), &b.attrs)
88}
89
90/// The keep of the block after `b`, if any.
91fn next_keep(m: &Model, b: &Blk) -> Option<usize> {
92 m.block(b.index + 1).map(|n| keep(Some(&b.attrs), &n.attrs))
93}
94
95/// Rewrites blocks `lo..`: each entry's attributes, its join from the wanted keep
96/// (None: as given). Then gives the following block keep `next` (its old keep).
97fn relink(m: &Model, lo: usize, new: Vec<(Attrs, Option<usize>)>, next: Option<usize>) {
98 let mut prev = lo.checked_sub(1).and_then(|i| m.block(i)).map(|b| b.attrs);
99 let mut out = Vec::with_capacity(new.len() + 1);
100 for (mut a, k) in new {
101 if let Some(k) = k {
102 a.join = join_for(prev.as_ref(), &a.wrap, k);
103 }
104 prev = Some(a.clone());
105 out.push(Some(a));
106 }
107 if let (Some(k), Some(b)) = (next, m.block(lo + out.len())) {
108 let mut a = b.attrs.clone();
109 a.join = join_for(prev.as_ref(), &a.wrap, k);
110 out.push(Some(a));
111 }
112 m.set_attrs(lo, &out);
113}
114
115/// Whether `cur` stays in the level-`d` node of `prev`: the same item, or with `list`
116/// the same list.
117fn same_node(prev: &Attrs, cur: &Attrs, d: usize, list: bool) -> bool {
118 let k = keep(Some(prev), cur);
119 k > d || (list && k == d && common(&prev.wrap, &cur.wrap) > d && cur.wrap[d].is_list())
120}
121
122/// Blocks `(first, last)` in the level-`d` node holding block `i`.
123fn extent(m: &Model, i: usize, d: usize, list: bool) -> (usize, usize) {
124 let cur = m.block(i).expect("block").attrs;
125 let (mut s, mut e) = (i, i);
126 let mut c = cur.clone();
127 m.scan(i, true, |info, a| {
128 if same_node(a, &c, d, list) {
129 s = info.index;
130 c = a.clone();
131 true
132 } else {
133 false
134 }
135 });
136 let mut p = cur;
137 m.scan(i + 1, false, |info, a| {
138 if same_node(&p, a, d, list) {
139 e = info.index;
140 p = a.clone();
141 true
142 } else {
143 false
144 }
145 });
146 (s, e)
147}
148
149/// Blocks `lo..=hi` with their old keeps.
150fn with_keeps(m: &Model, lo: usize, hi: usize) -> Vec<(Blk, usize)> {
151 let blocks = m.blocks(lo, hi + 1);
152 let mut prev = lo.checked_sub(1).and_then(|i| m.block(i)).map(|b| b.attrs);
153 blocks
154 .into_iter()
155 .map(|b| {
156 let k = keep(prev.as_ref(), &b.attrs);
157 prev = Some(b.attrs.clone());
158 (b, k)
159 })
160 .collect()
161}
162
163/// Deletes block `b` whole; the next block keeps what both shared with the one before.
164fn remove_block(m: &Model, b: &Blk) {
165 if m.len() == 1 {
166 m.delete(b.start, b.sep);
167 m.set_attrs(0, &[Some(Attrs::default())]);
168 return;
169 }
170 let kb = keep_of(m, b);
171 let kn = next_keep(m, b);
172 m.delete(b.start, b.end());
173 if let Some(kn) = kn {
174 relink(m, b.index, Vec::new(), Some(kn.min(kb)));
175 }
176}
177
178/// Inserts a block of `attrs` after `b`, keeping `k` levels with it. Returns its start.
179fn block_after(m: &Model, b: &Blk, mut attrs: Attrs, k: usize) -> Pos {
180 let nk = next_keep(m, b);
181 attrs.join = join_for(Some(&b.attrs), &attrs.wrap, k);
182 m.insert_blocks(b.end(), &[FlatBlock { attrs, ..Default::default() }]);
183 if let Some(nk) = nk {
184 relink(m, b.index + 2, Vec::new(), Some(nk));
185 }
186 b.end()
187}
188
189/// Inserts a block of `attrs` before `b`, taking `b`'s place; `b` then shares all its
190/// levels with it. Returns the new block's start.
191fn block_before(m: &Model, b: &Blk, mut attrs: Attrs) -> Pos {
192 let kb = keep_of(m, b);
193 attrs.join = None;
194 m.insert_blocks(b.start, &[FlatBlock { attrs: attrs.clone(), ..Default::default() }]);
195 let d = b.depth();
196 relink(m, b.index, vec![(attrs, Some(kb)), (b.attrs.clone(), Some(d))], None);
197 b.start
198}
199
200/// A paragraph in the containers of `b`.
201fn para_in(b: &Blk) -> Attrs {
202 Attrs { wrap: b.attrs.wrap.clone(), ..Attrs::default() }
203}
204
205/// Clears inline marks and drops images from `from..to` (text becoming code).
206fn to_plain(m: &Model, from: Pos, to: Pos) {
207 if from >= to {
208 return;
209 }
210 let (a, b) = (m.to_u(from), m.to_u(to));
211 m.restyle(INLINE.iter().map(|k| Seg { from: a, to: b, key: k, value: None }).collect());
212 let text: Vec<u16> = m.plain(from, to).encode_utf16().collect();
213 for (i, _) in text.iter().enumerate().rev().filter(|(_, c)| **c == flat::OBJ as u16) {
214 m.delete(from + i, from + i + 1);
215 }
216}
217
218// ---------------------------------------------------------------------------
219// Marks at a position
220// ---------------------------------------------------------------------------
221
222/// Marks of the first run of `from..to`; a break or image carries none.
223fn run_marks(m: &Model, from: Pos, to: Pos, last: bool) -> Option<Marks> {
224 let runs = m.slice(from, to);
225 let run = if last { runs.into_iter().last() } else { runs.into_iter().next() };
226 let TextDelta::Insert { insert, attributes } = run? else { return None };
227 let c = if last { insert.chars().last()? } else { insert.chars().next()? };
228 if c == '\n' || c == flat::OBJ || c == flat::SEP {
229 return Some(Marks::none());
230 }
231 Some(Marks::from_attrs(attributes.as_ref()))
232}
233
234/// PM `ResolvedPos.marks()`: inside a run its marks; at a boundary the marks of the
235/// run before (after, at the block start), minus a link that does not continue on the
236/// other side.
237pub fn marks_at(m: &Model, off: Pos) -> Marks {
238 let b = m.at(off);
239 if b.is_empty() || b.kind() != Leaf::Para && !matches!(b.kind(), Leaf::Heading(_)) {
240 return Marks::none();
241 }
242 let before = (off > b.start).then(|| run_marks(m, off.saturating_sub(2).max(b.start), off, true)).flatten();
243 let after = (off < b.sep).then(|| run_marks(m, off, (off + 2).min(b.sep), false)).flatten();
244 let (main, other) = match (before, after) {
245 (Some(x), a) => (x, a),
246 (None, Some(a)) => (a, None),
247 (None, None) => return Marks::none(),
248 };
249 let mut mk = main;
250 if mk.link.is_some() && other.is_none_or(|o| o.link != mk.link) {
251 mk.link = None;
252 }
253 mk
254}
255
256/// Marks the next inserted text gets.
257pub fn pending_marks(cx: &Cx) -> Marks {
258 if let Some(m) = &cx.stored {
259 return m.clone();
260 }
261 match cx.sel.cursor() {
262 Some(p) => marks_at(cx.m, p),
263 None => Marks::none(),
264 }
265}
266
267// ---------------------------------------------------------------------------
268// Text input
269// ---------------------------------------------------------------------------
270
271/// Replaces the selection with `text` carrying the pending marks.
272pub fn insert_text(cx: &mut Cx, text: &str) -> bool {
273 let marks = if cx.sel.is_empty() {
274 pending_marks(cx)
275 } else {
276 // Typing over a range takes the marks at its start (PM uses $from.marks()).
277 pos::text_range(cx.m, &cx.sel).map_or(Marks::none(), |(from, _)| {
278 let b = cx.m.at(from);
279 if from < b.sep { run_marks(cx.m, from, (from + 2).min(b.sep), false).unwrap_or_default() } else { marks_at(cx.m, from) }
280 })
281 };
282 if !cx.sel.is_empty() && !delete_selection(cx, true) {
283 return false;
284 }
285 let Some((b, off)) = cx.caret() else { return false };
286 let marks = if b.kind() == Leaf::Code { Marks::none() } else { marks };
287 let end = cx.m.insert(off, text, &marks);
288 cx.set_caret(end);
289 true
290}
291
292/// Inserts inline content (paste) at the selection.
293pub fn insert_inline(cx: &mut Cx, inl: &[Inline]) -> bool {
294 if !cx.sel.is_empty() && !delete_selection(cx, true) {
295 return false;
296 }
297 let Some((b, off)) = cx.caret() else { return false };
298 let end = if b.kind() == Leaf::Code { cx.m.insert(off, &inline_text(inl), &Marks::none()) } else { cx.m.insert_inline(off, inl) };
299 cx.set_caret(end);
300 true
301}
302
303fn inline_text(inl: &[Inline]) -> String {
304 inl.iter()
305 .map(|i| match i {
306 Inline::Text(s, _) => s.as_str(),
307 Inline::HardBreak => "\n",
308 Inline::Image { .. } => "",
309 })
310 .collect()
311}
312
313// ---------------------------------------------------------------------------
314// Deletion
315// ---------------------------------------------------------------------------
316
317pub fn delete_selection(cx: &mut Cx, apply: bool) -> bool {
318 match cx.sel {
319 Selection::Text { anchor, head } if anchor != head => {
320 if apply {
321 let (from, to) = (anchor.min(head), anchor.max(head));
322 delete_range(cx.m, from, to);
323 cx.set_caret(from);
324 }
325 true
326 }
327 Selection::All => {
328 if apply {
329 let last = cx.m.last();
330 cx.m.delete(0, last.sep);
331 cx.m.set_attrs(0, &[Some(Attrs::default())]);
332 cx.set_caret(0);
333 }
334 true
335 }
336 Selection::Node(p) => {
337 let b = cx.m.at(p);
338 if apply {
339 if b.kind() == Leaf::Rule {
340 remove_block(cx.m, &b);
341 let near = pos::snap(cx.m, b.start.min(cx.m.last().sep));
342 cx.set_caret(near);
343 } else {
344 // An image inside a text block: one char.
345 cx.m.delete(p, p + 1);
346 cx.set_caret(p);
347 }
348 }
349 true
350 }
351 _ => false,
352 }
353}
354
355/// Deletes `from..to`. Across blocks the merged block keeps the first block's
356/// attributes, and the block after the range keeps the levels it shared with the last
357/// one where those match the first one's.
358pub fn delete_range(m: &Model, from: Pos, to: Pos) {
359 let x = m.at(from);
360 let y = m.at(to);
361 if x.index == y.index {
362 m.delete(from, to);
363 return;
364 }
365 let kz = next_keep(m, &y);
366 let cw = common(&x.attrs.wrap, &y.attrs.wrap);
367 let tail = y.sep - to;
368 m.delete(from, to);
369 if x.kind() == Leaf::Code && y.kind() != Leaf::Code {
370 to_plain(m, from, from + tail);
371 }
372 relink(m, x.index, vec![(x.attrs.clone(), None)], kz.map(|k| k.min(cw)));
373}
374
375/// Merges block `b` into the block `a` before it (same containers). Returns the join point.
376fn join_into(m: &Model, a: &Blk, b: &Blk) -> Pos {
377 m.delete(a.sep, a.sep + 1);
378 m.set_attrs(a.index, &[Some(a.attrs.clone())]);
379 if a.kind() == Leaf::Code && b.kind() != Leaf::Code {
380 to_plain(m, a.sep, a.sep + b.len());
381 }
382 a.sep
383}
384
385pub fn join_backward(cx: &mut Cx, apply: bool) -> bool {
386 let Some((b, off)) = cx.caret() else { return false };
387 if off != b.start {
388 return false;
389 }
390 let m = cx.m;
391 let Some(a) = prev_of(m, &b) else { return lift(cx, &b, apply) };
392 let k = keep(Some(&a.attrs), &b.attrs);
393 let l = b.depth();
394 if k < l {
395 // First in a container: join the previous one of its kind, else leave it.
396 if common(&a.attrs.wrap, &b.attrs.wrap) > k {
397 if apply {
398 let nk = next_keep(m, &b);
399 relink(m, b.index, vec![(b.attrs.clone(), Some(k + 1))], nk);
400 }
401 return true;
402 }
403 return lift(cx, &b, apply);
404 }
405 if a.depth() > l {
406 // After a container: move into its trailing item or quote.
407 let mut n = l + 1;
408 while n < a.depth() && a.attrs.wrap[n] == Wrap::Quote {
409 n += 1;
410 }
411 if apply {
412 let nk = next_keep(m, &b);
413 let mut at = b.attrs.clone();
414 at.wrap = a.attrs.wrap[..n].to_vec();
415 relink(m, b.index, vec![(at, Some(n))], nk);
416 }
417 return true;
418 }
419 if !apply {
420 return true;
421 }
422 if a.kind() == Leaf::Rule {
423 if b.is_empty() {
424 remove_block(m, &b);
425 cx.sel = Selection::Node(a.start);
426 } else {
427 remove_block(m, &a);
428 cx.set_caret(a.start);
429 }
430 } else if a.is_empty() {
431 remove_block(m, &a);
432 cx.set_caret(a.start);
433 } else {
434 let at = join_into(m, &a, &b);
435 cx.set_caret(at);
436 }
437 true
438}
439
440pub fn join_forward(cx: &mut Cx, apply: bool) -> bool {
441 let Some((b, off)) = cx.caret() else { return false };
442 if off != b.sep {
443 return false;
444 }
445 let m = cx.m;
446 let Some(c) = m.block(b.index + 1) else { return false };
447 let k = keep(Some(&b.attrs), &c.attrs);
448 let l = c.depth();
449 if b.is_empty() {
450 if apply {
451 remove_block(m, &b);
452 cx.sel = if c.kind() == Leaf::Rule { Selection::Node(b.start) } else { Selection::caret(b.start) };
453 }
454 return true;
455 }
456 if k < l {
457 if common(&b.attrs.wrap, &c.attrs.wrap) > k {
458 if apply {
459 let nk = next_keep(m, &c);
460 relink(m, c.index, vec![(c.attrs.clone(), Some(k + 1))], nk);
461 }
462 return true;
463 }
464 let sel = cx.sel.clone();
465 let ran = lift(cx, &c, apply);
466 cx.sel = sel;
467 return ran;
468 }
469 if b.depth() > l {
470 return false;
471 }
472 if apply {
473 if c.kind() == Leaf::Rule {
474 remove_block(m, &c);
475 } else {
476 join_into(m, &b, &c);
477 }
478 cx.set_caret(b.sep);
479 }
480 true
481}
482
483pub fn select_node_backward(cx: &mut Cx, apply: bool) -> bool {
484 let Some((b, off)) = cx.caret() else { return false };
485 if off != b.start {
486 return false;
487 }
488 match prev_of(cx.m, &b) {
489 Some(a) if a.kind() == Leaf::Rule => {
490 if apply {
491 cx.sel = Selection::Node(a.start);
492 }
493 true
494 }
495 _ => false,
496 }
497}
498
499pub fn select_node_forward(cx: &mut Cx, apply: bool) -> bool {
500 let Some((b, off)) = cx.caret() else { return false };
501 if off != b.sep {
502 return false;
503 }
504 match cx.m.block(b.index + 1) {
505 Some(c) if c.kind() == Leaf::Rule => {
506 if apply {
507 cx.sel = Selection::Node(c.start);
508 }
509 true
510 }
511 _ => false,
512 }
513}
514
515// ---------------------------------------------------------------------------
516// Enter
517// ---------------------------------------------------------------------------
518
519pub fn newline_in_code(cx: &mut Cx, apply: bool) -> bool {
520 let Some(b) = cx.head_block() else { return false };
521 if b.kind() != Leaf::Code {
522 return false;
523 }
524 if let Selection::Text { anchor, .. } = cx.sel
525 && !b.holds(anchor)
526 {
527 return false;
528 }
529 !apply || insert_text(cx, "\n")
530}
531
532pub fn create_paragraph_near(cx: &mut Cx, apply: bool) -> bool {
533 let m = cx.m;
534 match cx.sel {
535 Selection::Node(p) => {
536 let b = m.at(p);
537 if b.kind() != Leaf::Rule {
538 return false;
539 }
540 if apply {
541 let at = if b.index == 0 { block_before(m, &b, para_in(&b)) } else { block_after(m, &b, para_in(&b), b.depth()) };
542 cx.set_caret(at);
543 }
544 true
545 }
546 Selection::Gap(p) => {
547 if apply {
548 let at = if p < m.total() {
549 let b = m.at(p);
550 let mut a = para_in(&b);
551 a.start = b.attrs.start;
552 block_before(m, &b, a)
553 } else {
554 let b = m.last();
555 block_after(m, &b, para_in(&b), b.depth())
556 };
557 cx.set_caret(at);
558 }
559 true
560 }
561 _ => false,
562 }
563}
564
565pub fn lift_empty_block(cx: &mut Cx, apply: bool) -> bool {
566 let Some((b, _)) = cx.caret() else { return false };
567 if !b.is_empty() || b.depth() == 0 {
568 return false;
569 }
570 lift(cx, &b, apply)
571}
572
573pub fn split_block(cx: &mut Cx, apply: bool) -> bool {
574 if !matches!(cx.sel, Selection::Text { .. }) {
575 return false;
576 }
577 if !apply {
578 return true;
579 }
580 if !cx.sel.is_empty() {
581 delete_selection(cx, true);
582 }
583 let Some((b, off)) = cx.caret() else { return false };
584 let at_end = off == b.sep;
585 let mut first = b.attrs.clone();
586 if off == b.start && !at_end && b.kind() != Leaf::Para {
587 // Enter at the start of a heading: the empty first half is a paragraph.
588 first.kind = Leaf::Para;
589 first.lang = None;
590 }
591 let tail = Attrs {
592 kind: if at_end { Leaf::Para } else { b.kind() },
593 lang: if at_end { None } else { b.attrs.lang.clone() },
594 wrap: b.attrs.wrap.clone(),
595 join: None,
596 start: None,
597 };
598 let m = cx.m;
599 m.insert_blocks(off, &[FlatBlock { attrs: first, ..Default::default() }]);
600 relink(m, b.index + 1, vec![(tail, Some(b.depth()))], None);
601 cx.set_caret(off + 1);
602 true
603}
604
605pub fn exit_code(cx: &mut Cx, apply: bool) -> bool {
606 let Some(b) = cx.head_block() else { return false };
607 if b.kind() != Leaf::Code {
608 return false;
609 }
610 if apply {
611 let at = block_after(cx.m, &b, para_in(&b), b.depth());
612 cx.set_caret(at);
613 }
614 true
615}
616
617pub fn select_all(cx: &mut Cx, apply: bool) -> bool {
618 if apply {
619 cx.sel = Selection::All;
620 }
621 true
622}
623
624// ---------------------------------------------------------------------------
625// Lists and quotes
626// ---------------------------------------------------------------------------
627
628/// Moves block `b` out of its innermost container: its list item, or its quote.
629fn lift(cx: &mut Cx, b: &Blk, apply: bool) -> bool {
630 let l = b.depth();
631 if l == 0 {
632 return false;
633 }
634 let d = l - 1;
635 if b.attrs.wrap[d].is_list() {
636 return lift_item(cx.m, b.index, d, apply);
637 }
638 if apply {
639 pop_level(cx.m, b, d);
640 }
641 true
642}
643
644/// Removes the innermost level `d` of a single block; what followed in that
645/// container opens a new one after it.
646fn pop_level(m: &Model, b: &Blk, d: usize) {
647 let kb = keep_of(m, b);
648 let kn = next_keep(m, b);
649 let mut a = b.attrs.clone();
650 a.wrap.truncate(d);
651 relink(m, b.index, vec![(a, Some(kb.min(d)))], kn.map(|k| k.min(d)));
652}
653
654/// liftListItem for the item at level `d` holding block `i`: the item leaves that
655/// list. Nested, it becomes an item of the outer list and the items after it a list
656/// inside it; at the top its blocks replace it and the list continues after them.
657fn lift_item(m: &Model, i: usize, d: usize, apply: bool) -> bool {
658 if !apply {
659 return true;
660 }
661 let (s, e) = extent(m, i, d, false);
662 let blocks = with_keeps(m, s, e);
663 let first = &blocks[0].0;
664 let nested = d > 0 && first.attrs.wrap[d - 1].is_list();
665 let next = m.block(e + 1);
666 let next_is_item = next.as_ref().is_some_and(|n| same_node(&blocks.last().unwrap().0.attrs, &n.attrs, d, true));
667 let nk = next.as_ref().map(|n| if next_is_item { d } else { keep(Some(&blocks.last().unwrap().0.attrs), &n.attrs) });
668 let new = blocks
669 .iter()
670 .enumerate()
671 .map(|(j, (b, k))| {
672 let mut a = b.attrs.clone();
673 a.wrap.remove(d);
674 let k = if j == 0 { (*k).min(if nested { d - 1 } else { d }) } else { k - 1 };
675 if j == 0 {
676 a.start = None;
677 }
678 (a, Some(k))
679 })
680 .collect();
681 relink(m, s, new, nk);
682 true
683}
684
685/// The innermost list level of block `b` that it sits in directly.
686fn item_level(b: &Blk) -> Option<usize> {
687 let d = b.depth().checked_sub(1)?;
688 b.attrs.wrap[d].is_list().then_some(d)
689}
690
691pub fn split_list_item(cx: &mut Cx, apply: bool) -> bool {
692 let Some(b) = cx.head_block() else { return false };
693 if !matches!(cx.sel, Selection::Text { .. }) || !b.kind().is_text() {
694 return false;
695 }
696 let Some(d) = item_level(&b) else { return false };
697 let m = cx.m;
698 let kb = keep_of(m, &b);
699 let last_in_item = m.block(b.index + 1).is_none_or(|n| keep(Some(&b.attrs), &n.attrs) <= d);
700 if b.is_empty() && last_in_item && cx.sel.is_empty() {
701 if kb <= d {
702 // An empty item: Enter leaves the list.
703 return lift_item(m, b.index, d, apply);
704 }
705 // An empty last paragraph of an item becomes the next item.
706 if apply {
707 let nk = next_keep(m, &b);
708 relink(m, b.index, vec![(b.attrs.clone(), Some(d))], nk);
709 }
710 return true;
711 }
712 if !apply {
713 return true;
714 }
715 if !cx.sel.is_empty() {
716 delete_selection(cx, true);
717 }
718 let Some((b, off)) = cx.caret() else { return false };
719 let tail = Attrs { wrap: b.attrs.wrap.clone(), ..Attrs::default() };
720 m.insert_blocks(off, &[FlatBlock { attrs: b.attrs.clone(), ..Default::default() }]);
721 relink(m, b.index + 1, vec![(tail, Some(d))], None);
722 cx.set_caret(off + 1);
723 true
724}
725
726pub fn sink_list_item(cx: &mut Cx, apply: bool) -> bool {
727 let Some(b) = cx.head_block() else { return false };
728 let Some(d) = item_level(&b) else { return false };
729 let m = cx.m;
730 let (s, e) = extent(m, b.index, d, false);
731 let first = m.block(s).unwrap();
732 // Only an item with an item before it in the same list can sink.
733 let Some(p) = prev_of(m, &first) else { return false };
734 if !same_node(&p.attrs, &first.attrs, d, true) {
735 return false;
736 }
737 if !apply {
738 return true;
739 }
740 let w = b.attrs.wrap[d];
741 let blocks = with_keeps(m, s, e);
742 let nk = m.block(e + 1).map(|n| keep(Some(&blocks.last().unwrap().0.attrs), &n.attrs));
743 let new = blocks
744 .iter()
745 .enumerate()
746 .map(|(j, (b, k))| {
747 let mut a = b.attrs.clone();
748 a.wrap.insert(d + 1, w);
749 (a, Some(if j == 0 { d + 1 } else { k + 1 }))
750 })
751 .collect();
752 relink(m, s, new, nk);
753 true
754}
755
756pub fn lift_list_item(cx: &mut Cx, apply: bool) -> bool {
757 let Some(b) = cx.head_block() else { return false };
758 let Some(d) = b.attrs.wrap.iter().rposition(|w| w.is_list()) else { return false };
759 lift_item(cx.m, b.index, d, apply)
760}
761
762/// Wraps the blocks of the selection (whole nodes at their deepest common level) in a
763/// new list or quote.
764fn wrap_range(cx: &mut Cx, w: Wrap, apply: bool) -> bool {
765 let m = cx.m;
766 let Some((from, to)) = pos::text_range(m, &cx.sel) else { return false };
767 let (x, y) = (m.at(from), m.at(to));
768 let range = with_keeps(m, x.index, y.index);
769 if range.is_empty() {
770 return false;
771 }
772 let mut d = x.depth();
773 for (b, k) in &range[1..] {
774 d = d.min(*k).min(b.depth());
775 }
776 let (s, _) = if x.index == 0 || keep_of(m, &x) <= d { (x.index, 0) } else { extent(m, x.index, d, false) };
777 let (_, e) = if y.depth() <= d { (0, y.index) } else { extent(m, y.index, d, false) };
778 let blocks = with_keeps(m, s, e);
779 let first = &blocks[0];
780 // The first block of a list item stays its first block.
781 if d > 0 && first.0.attrs.wrap[d - 1].is_list() && first.1 < d {
782 return false;
783 }
784 if w.is_list() {
785 let mut prev = &blocks[0].0;
786 for (b, k) in &blocks[1..] {
787 if *k == d && same_node(&prev.attrs, &b.attrs, d, true) && b.depth() > d {
788 return false;
789 }
790 prev = b;
791 }
792 }
793 if !apply {
794 return true;
795 }
796 let nk = m.block(e + 1).map(|n| keep(Some(&blocks.last().unwrap().0.attrs), &n.attrs));
797 let new = blocks
798 .iter()
799 .enumerate()
800 .map(|(j, (b, k))| {
801 let mut a = b.attrs.clone();
802 a.wrap.insert(d, w);
803 let k = match j {
804 0 => *k,
805 _ if w.is_list() && *k == d => d,
806 _ => k + 1,
807 };
808 (a, Some(k))
809 })
810 .collect();
811 relink(m, s, new, nk);
812 true
813}
814
815pub fn wrap_in_list(cx: &mut Cx, kind: Kind, start: Option<i64>, apply: bool) -> bool {
816 let Some(w) = kind.wrap().filter(|w| w.is_list()) else { return false };
817 let ran = wrap_range(cx, w, apply);
818 if ran
819 && apply
820 && let Some(n) = start.filter(|&n| n != 1)
821 && let Some((from, _)) = pos::text_range(cx.m, &cx.sel)
822 {
823 let b = cx.m.at(from);
824 let mut a = b.attrs.clone();
825 a.start = Some(n);
826 cx.m.set_attrs(b.index, &[Some(a)]);
827 }
828 ran
829}
830
831pub fn wrap_in(cx: &mut Cx, kind: Kind, apply: bool) -> bool {
832 match kind.wrap() {
833 Some(w) => wrap_range(cx, w, apply),
834 None => false,
835 }
836}
837
838/// Changes the type of the list at level `d` holding block `i`.
839fn retype_list(m: &Model, i: usize, d: usize, w: Wrap) {
840 let (s, e) = extent(m, i, d, true);
841 let blocks = with_keeps(m, s, e);
842 let nk = m.block(e + 1).map(|n| keep(Some(&blocks.last().unwrap().0.attrs), &n.attrs));
843 let new = blocks
844 .into_iter()
845 .map(|(b, k)| {
846 let mut a = b.attrs;
847 a.wrap[d] = w;
848 (a, Some(k))
849 })
850 .collect();
851 relink(m, s, new, nk);
852}
853
854/// The innermost container of the head block matching `pred`.
855pub fn ancestor_kind(cx: &Cx, pred: fn(Kind) -> bool) -> Option<Kind> {
856 let b = cx.head_block()?;
857 b.attrs.wrap.iter().rev().map(|w| Kind::of_wrap(*w)).find(|k| pred(*k))
858}
859
860pub fn toggle_list(cx: &mut Cx, kind: Kind, apply: bool) -> bool {
861 let Some(w) = kind.wrap() else { return false };
862 let Some(b) = cx.head_block() else { return false };
863 match b.attrs.wrap.iter().rposition(|x| x.is_list()) {
864 None => wrap_range(cx, w, apply),
865 Some(d) if b.attrs.wrap[d] == w => lift_item(cx.m, b.index, d, apply),
866 Some(d) => {
867 if apply {
868 retype_list(cx.m, b.index, d, w);
869 }
870 true
871 }
872 }
873}
874
875pub fn toggle_quote(cx: &mut Cx, apply: bool) -> bool {
876 let Some(b) = cx.head_block() else { return false };
877 let Some(q) = b.attrs.wrap.iter().rposition(|w| *w == Wrap::Quote) else { return wrap_range(cx, Wrap::Quote, apply) };
878 if !apply {
879 return true;
880 }
881 // The quote's child holding the block leaves it; the quote splits around it.
882 let m = cx.m;
883 let (s, e) = if b.depth() > q + 1 { extent(m, b.index, q + 1, true) } else { (b.index, b.index) };
884 let blocks = with_keeps(m, s, e);
885 let nk = m.block(e + 1).map(|n| keep(Some(&blocks.last().unwrap().0.attrs), &n.attrs).min(q));
886 let new = blocks
887 .iter()
888 .enumerate()
889 .map(|(j, (b, k))| {
890 let mut a = b.attrs.clone();
891 a.wrap.remove(q);
892 (a, Some(if j == 0 { (*k).min(q) } else { k - 1 }))
893 })
894 .collect();
895 relink(m, s, new, nk);
896 true
897}
898
899// ---------------------------------------------------------------------------
900// Block types
901// ---------------------------------------------------------------------------
902
903/// Text blocks from the one holding `from` through the one holding `to`.
904fn text_blocks(m: &Model, from: Pos, to: Pos) -> Vec<Blk> {
905 let (x, y) = (m.at(from), m.at(to));
906 m.blocks(x.index, y.index + 1).into_iter().filter(|b| b.kind().is_text()).collect()
907}
908
909/// Whether block `b` may become `kind`: the first block of a list item stays a paragraph.
910pub fn can_retype(m: &Model, b: &Blk, kind: Leaf) -> bool {
911 match item_level(b) {
912 Some(d) if keep_of(m, b) <= d => kind == Leaf::Para,
913 _ => true,
914 }
915}
916
917pub fn set_block_type(cx: &mut Cx, kind: Kind, apply: bool) -> bool {
918 let Some(leaf) = kind.leaf() else { return false };
919 let m = cx.m;
920 let Some((from, to)) = pos::text_range(m, &cx.sel) else { return false };
921 let (x, y) = (m.at(from), m.at(to));
922 if !apply {
923 // A dry run (toolbar state) stops at the first block it could retype.
924 let mut found = false;
925 m.scan(x.index, false, |info, a| {
926 if info.index > y.index {
927 return false;
928 }
929 if a.kind.is_text() && a.kind != leaf {
930 let b = m.block(info.index).unwrap();
931 found = can_retype(m, &b, leaf);
932 }
933 !found
934 });
935 return found;
936 }
937 let blocks: Vec<Blk> = text_blocks(m, from, to).into_iter().filter(|b| can_retype(m, b, leaf)).collect();
938 if !blocks.iter().any(|b| b.kind() != leaf) {
939 return false;
940 }
941 if leaf == Leaf::Code {
942 // Adjacent blocks in one container become one code block, a line each.
943 let mut runs: Vec<Vec<Blk>> = Vec::new();
944 for b in blocks {
945 match runs.last_mut() {
946 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),
947 _ => runs.push(vec![b]),
948 }
949 }
950 for run in runs.iter().rev() {
951 let (first, last) = (&run[0], run.last().unwrap());
952 to_plain(m, first.start, last.sep);
953 let seps: Vec<(Pos, Option<Attrs>)> = (first.index..last.index).map(|i| (m.block(i).unwrap().sep, None)).collect();
954 m.swap_chars(seps);
955 let mut a = first.attrs.clone();
956 a.kind = Leaf::Code;
957 a.lang = None;
958 m.set_attrs(first.index, &[Some(a)]);
959 }
960 } else {
961 // A code block becomes one block per line.
962 for b in blocks.iter().rev().filter(|b| b.kind() == Leaf::Code) {
963 let text: Vec<u16> = m.plain(b.start, b.sep).encode_utf16().collect();
964 let breaks: Vec<usize> = text.iter().enumerate().filter(|(_, c)| **c == b'\n' as u16).map(|(i, _)| b.start + i).collect();
965 if breaks.is_empty() {
966 continue;
967 }
968 let mut first = b.attrs.clone();
969 first.kind = leaf;
970 first.lang = None;
971 let rest = Attrs { kind: leaf, wrap: b.attrs.wrap.clone(), join: join_for(Some(&b.attrs), &b.attrs.wrap, b.depth()), ..Attrs::default() };
972 let mut swaps = vec![(breaks[0], Some(first))];
973 swaps.extend(breaks[1..].iter().map(|&p| (p, Some(rest.clone()))));
974 m.swap_chars(swaps);
975 let last = m.block(b.index + breaks.len()).unwrap();
976 m.set_attrs(last.index, &[Some(rest.clone())]);
977 }
978 let targets: Vec<Blk> = text_blocks(m, from, to).into_iter().filter(|b| b.kind() != leaf && can_retype(m, b, leaf)).collect();
979 let mut changes: Vec<(usize, Attrs)> = Vec::new();
980 for b in targets {
981 let mut a = b.attrs.clone();
982 a.kind = leaf;
983 a.lang = None;
984 changes.push((b.index, a));
985 }
986 set_many(m, changes);
987 }
988 cx.sel = pos::clamp(m, &cx.sel);
989 true
990}
991
992/// Sets attributes of scattered blocks (sorted), as few runs as possible.
993fn set_many(m: &Model, changes: Vec<(usize, Attrs)>) {
994 let Some(lo) = changes.first().map(|c| c.0) else { return };
995 let hi = changes.last().unwrap().0;
996 let mut new = vec![None; hi - lo + 1];
997 for (i, a) in changes {
998 new[i - lo] = Some(a);
999 }
1000 m.set_attrs(lo, &new);
1001}
1002
1003pub fn is_block_active(cx: &Cx, kind: Kind) -> bool {
1004 cx.head_block().is_some_and(|b| Some(b.kind()) == kind.leaf())
1005}
1006
1007pub fn toggle_block(cx: &mut Cx, kind: Kind, apply: bool) -> bool {
1008 if is_block_active(cx, kind) { set_block_type(cx, Kind::Paragraph, apply) } else { set_block_type(cx, kind, apply) }
1009}
1010
1011/// Sets the language of the code block holding `off` (None: detect).
1012pub fn set_code_language(m: &Model, off: Pos, lang: Option<&str>) -> bool {
1013 let b = m.at(off);
1014 if b.kind() != Leaf::Code {
1015 return false;
1016 }
1017 let mut a = b.attrs.clone();
1018 a.lang = lang.filter(|l| !l.is_empty()).map(str::to_owned);
1019 if a == b.attrs {
1020 return false;
1021 }
1022 m.set_attrs(b.index, &[Some(a)]);
1023 true
1024}
1025
1026pub fn insert_rule(cx: &mut Cx, apply: bool) -> bool {
1027 let Some(b) = cx.head_block() else { return false };
1028 if b.kind() == Leaf::Code || !b.kind().is_text() {
1029 return false;
1030 }
1031 if !apply {
1032 return true;
1033 }
1034 if !cx.sel.is_empty() {
1035 delete_selection(cx, true);
1036 }
1037 let Some((b, off)) = cx.caret() else { return false };
1038 let m = cx.m;
1039 let rule = Attrs { kind: Leaf::Rule, wrap: b.attrs.wrap.clone(), ..Attrs::default() };
1040 let l = b.depth();
1041 if off == b.start {
1042 let at = block_before(m, &b, Attrs { start: b.attrs.start, ..rule });
1043 cx.set_caret(at + 1);
1044 } else if off == b.sep {
1045 block_after(m, &b, rule, l);
1046 let r = m.block(b.index + 1).unwrap();
1047 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);
1048 let at = match next {
1049 Some(n) => n.start,
1050 None => block_after(m, &r, para_in(&b), l),
1051 };
1052 cx.set_caret(at);
1053 } else {
1054 // Split, with the rule between the halves.
1055 let tail = Attrs { kind: b.kind(), lang: b.attrs.lang.clone(), wrap: b.attrs.wrap.clone(), ..Attrs::default() };
1056 m.insert_blocks(off, &[FlatBlock { attrs: b.attrs.clone(), ..Default::default() }, FlatBlock { attrs: rule.clone(), ..Default::default() }]);
1057 relink(m, b.index + 1, vec![(rule, Some(l)), (tail, Some(l))], None);
1058 cx.set_caret(off + 2);
1059 }
1060 true
1061}
1062
1063// ---------------------------------------------------------------------------
1064// Inline marks
1065// ---------------------------------------------------------------------------
1066
1067/// Content ranges of the non-code blocks in `from..to`, one per run of neighbours
1068/// (a mark may cover the separators between them).
1069fn mark_ranges(m: &Model, from: Pos, to: Pos) -> Vec<(Pos, Pos)> {
1070 let (x, y) = (m.at(from), m.at(to));
1071 let mut out: Vec<(Pos, Pos)> = Vec::new();
1072 let mut open = false;
1073 m.scan(x.index, false, |info, a| {
1074 if info.index > y.index {
1075 return false;
1076 }
1077 if a.kind == Leaf::Code {
1078 open = false;
1079 return true;
1080 }
1081 let (s, e) = (info.start16.max(from), info.sep16().min(to));
1082 match out.last_mut() {
1083 Some(r) if open => r.1 = e,
1084 _ => out.push((s, e)),
1085 }
1086 open = true;
1087 true
1088 });
1089 out.retain(|r| r.0 < r.1);
1090 out
1091}
1092
1093/// Whether `from..to` holds text outside code blocks.
1094fn has_markable(m: &Model, from: Pos, to: Pos) -> bool {
1095 let (x, y) = (m.at(from), m.at(to));
1096 let mut found = false;
1097 m.scan(x.index, false, |info, a| {
1098 if info.index > y.index {
1099 return false;
1100 }
1101 found = a.kind != Leaf::Code && info.start16.max(from) < info.sep16().min(to);
1102 !found
1103 });
1104 found
1105}
1106
1107/// Whether mark `t` is on the stored marks (collapsed) or on any text of the
1108/// selection, looking at most at `limit` UTF-16 units of it.
1109pub fn mark_active_within(cx: &Cx, t: MarkType, limit: usize) -> bool {
1110 if cx.sel.is_empty() {
1111 return pending_marks(cx).has(t);
1112 }
1113 let Some((from, to)) = pos::text_range(cx.m, &cx.sel) else { return false };
1114 let to = to.min(from.saturating_add(limit));
1115 mark_ranges(cx.m, from, to).into_iter().any(|(a, b)| {
1116 cx.m.slice(a, b).into_iter().any(|d| match d {
1117 TextDelta::Insert { insert, attributes } => {
1118 Marks::from_attrs(attributes.as_ref()).has(t) && insert.chars().any(|c| c != flat::SEP)
1119 }
1120 _ => false,
1121 })
1122 })
1123}
1124
1125/// Units of the selection the toolbar looks at for mark state.
1126pub const MARK_STATE_UNITS: usize = 1 << 16;
1127
1128pub fn is_mark_active(cx: &Cx, t: MarkType) -> bool {
1129 mark_active_within(cx, t, usize::MAX)
1130}
1131
1132fn is_space(c: u16) -> bool {
1133 c == b' ' as u16 || c == b'\t' as u16 || c == b'\n' as u16 || c == 0xa0 || c == flat::SEP as u16
1134}
1135
1136/// `(a, b)` without surrounding whitespace, reading only near the ends.
1137fn trim(m: &Model, mut a: Pos, mut b: Pos) -> (Pos, Pos) {
1138 while a < b {
1139 let n = (b - a).min(256);
1140 let s: Vec<u16> = m.plain(a, a + n).encode_utf16().collect();
1141 let k = s.iter().take_while(|c| is_space(**c)).count();
1142 a += k;
1143 if k < n {
1144 break;
1145 }
1146 }
1147 while b > a {
1148 let n = (b - a).min(256);
1149 let s: Vec<u16> = m.plain(b - n, b).encode_utf16().collect();
1150 let k = s.iter().rev().take_while(|c| is_space(**c)).count();
1151 b -= k;
1152 if k < n {
1153 break;
1154 }
1155 }
1156 (a, b)
1157}
1158
1159fn mark_value(t: MarkType, link: Option<Link>) -> Option<LoroValue> {
1160 let mut mk = Marks::none();
1161 match t {
1162 MarkType::Link => mk.link = link,
1163 t => mk.set(t, true),
1164 }
1165 mk.value_of(t.key())
1166}
1167
1168/// Adds mark `t` over the text of `from..to` (input rules).
1169pub fn add_mark(m: &Model, from: Pos, to: Pos, t: MarkType) {
1170 style(m, mark_ranges(m, from, to), t, mark_value(t, None));
1171}
1172
1173fn style(m: &Model, ranges: Vec<(Pos, Pos)>, t: MarkType, value: Option<LoroValue>) {
1174 let segs = ranges
1175 .into_iter()
1176 .filter(|r| r.0 < r.1)
1177 .map(|(a, b)| Seg { from: m.to_u(a), to: m.to_u(b), key: t.key(), value: value.clone() })
1178 .collect();
1179 m.restyle(segs);
1180}
1181
1182pub fn toggle_mark(cx: &mut Cx, t: MarkType, apply: bool) -> bool {
1183 if cx.sel.is_empty() {
1184 let Some(b) = cx.head_block() else { return false };
1185 if b.kind() == Leaf::Code {
1186 return false;
1187 }
1188 if apply {
1189 let mut mk = pending_marks(cx);
1190 let on = !mk.has(t);
1191 mk.set(t, on);
1192 cx.stored = Some(mk);
1193 }
1194 return true;
1195 }
1196 let Some((from, to)) = pos::text_range(cx.m, &cx.sel) else { return false };
1197 if !apply {
1198 return has_markable(cx.m, from, to);
1199 }
1200 let ranges = mark_ranges(cx.m, from, to);
1201 if ranges.is_empty() {
1202 return false;
1203 }
1204 let remove = is_mark_active(cx, t);
1205 let ranges = if remove { ranges } else { ranges.into_iter().map(|(a, b)| trim(cx.m, a, b)).collect() };
1206 style(cx.m, ranges, t, if remove { None } else { mark_value(t, None) });
1207 true
1208}
1209
1210/// Sets or clears the link over `from..to`.
1211pub fn set_link(cx: &mut Cx, from: Pos, to: Pos, href: Option<&str>) {
1212 let link = href.map(|h| Link { href: h.to_owned(), title: None });
1213 let value = link.is_some().then(|| mark_value(MarkType::Link, link)).flatten();
1214 style(cx.m, mark_ranges(cx.m, from, to), MarkType::Link, value);
1215}
1216
1217/// The link around `off`, within its block: `(from, to, link)`.
1218pub fn link_range_at(m: &Model, off: Pos) -> Option<(Pos, Pos, Link)> {
1219 let b = m.at(off);
1220 if b.kind() == Leaf::Code || b.is_empty() {
1221 return None;
1222 }
1223 // Most carets touch no link: check the neighbouring units before reading further.
1224 let near = m.slice(off.saturating_sub(1).max(b.start), (off + 1).min(b.sep));
1225 let link = near.iter().find_map(|d| match d {
1226 TextDelta::Insert { attributes, .. } => Marks::from_attrs(attributes.as_ref()).link,
1227 _ => None,
1228 })?;
1229 let mut pos = b.start;
1230 let mut found: Option<(Pos, Pos)> = None;
1231 for d in m.slice(b.start, b.sep) {
1232 let TextDelta::Insert { insert, attributes } = d else { continue };
1233 let len = insert.encode_utf16().count();
1234 if Marks::from_attrs(attributes.as_ref()).link.as_ref() == Some(&link) {
1235 found = match found {
1236 Some((a, e)) if e == pos => Some((a, pos + len)),
1237 Some(r) if r.1 >= off => break,
1238 _ => Some((pos, pos + len)),
1239 };
1240 } else if found.is_some_and(|r| r.1 >= off) {
1241 break;
1242 }
1243 pos += len;
1244 }
1245 found.filter(|r| r.0 <= off && off <= r.1).map(|(a, e)| (a, e, link))
1246}
1247
1248/// Whether the link popover may open: a text selection in non-code text, or a caret
1249/// inside a link (the TS `toggleLink`).
1250pub fn can_link(cx: &Cx) -> bool {
1251 if let Some(p) = cx.sel.cursor() {
1252 return link_range_at(cx.m, p).is_some();
1253 }
1254 match pos::text_range(cx.m, &cx.sel) {
1255 Some((from, to)) if from < to => has_markable(cx.m, from, to),
1256 _ => false,
1257 }
1258}
1259
1260// ---------------------------------------------------------------------------
1261// Paste and copy
1262// ---------------------------------------------------------------------------
1263
1264fn block_lines(b: &Block, out: &mut Vec<String>) {
1265 match b {
1266 Block::Paragraph(v) | Block::Heading(_, v) => out.push(inline_text(v)),
1267 Block::Code { text, .. } => out.push(text.clone()),
1268 Block::Quote(bs) => bs.iter().for_each(|b| block_lines(b, out)),
1269 Block::List { items, .. } => items.iter().flatten().for_each(|b| block_lines(b, out)),
1270 Block::Rule => {}
1271 }
1272}
1273
1274/// Replaces the selection with pasted blocks, like PM's `replaceSelection`: the first
1275/// block's text joins the caret's block, the rest follow inside the caret block's
1276/// containers, and the text after the caret joins the last pasted block.
1277pub fn insert_blocks(cx: &mut Cx, blocks: &[Block]) -> bool {
1278 if blocks.is_empty() {
1279 return false;
1280 }
1281 if !cx.sel.is_empty() && !delete_selection(cx, true) {
1282 return false;
1283 }
1284 let Some((b, off)) = cx.caret() else { return false };
1285 if b.kind() == Leaf::Code {
1286 let mut lines = Vec::new();
1287 blocks.iter().for_each(|x| block_lines(x, &mut lines));
1288 return insert_text(cx, &lines.join("\n"));
1289 }
1290 let m = cx.m;
1291 let mut flat = flat::flatten(blocks);
1292 let inline = |f: &FlatBlock| f.attrs.wrap.is_empty() && matches!(f.attrs.kind, Leaf::Para | Leaf::Heading(_));
1293 if flat.len() == 1 && inline(&flat[0]) {
1294 return insert_inline(cx, &flat[0].inl);
1295 }
1296 // Keeps inside the paste, then shifted under the caret block's containers.
1297 let l = b.depth();
1298 let mut keeps = Vec::with_capacity(flat.len());
1299 let mut prev: Option<Attrs> = None;
1300 for f in &flat {
1301 keeps.push(keep(prev.as_ref(), &f.attrs) + l);
1302 prev = Some(f.attrs.clone());
1303 }
1304 for f in &mut flat {
1305 let mut w = b.attrs.wrap.clone();
1306 w.extend_from_slice(&f.attrs.wrap);
1307 f.attrs.wrap = w;
1308 f.attrs.join = None;
1309 }
1310 let head_inline = inline(&flat[0]);
1311 let head_empty = off == b.start && !head_inline;
1312 let tail_empty = off == b.sep;
1313 let n = flat.len();
1314 let merge_last = (n > 1 || !head_inline) && (inline(&flat[n - 1]) || tail_empty);
1315 let nk = next_keep(m, &b);
1316 let kb = keep_of(m, &b);
1317
1318 let mut at = off;
1319 if head_inline {
1320 at = m.insert_inline(at, &flat[0].inl);
1321 }
1322 let lo = if head_inline { 1 } else { 0 };
1323 let hi = if merge_last { n - 1 } else { n };
1324 let mut written: Vec<FlatBlock> = Vec::new();
1325 // (attrs, keep) of each block from the caret block on, for relink.
1326 let mut entries: Vec<(Attrs, Option<usize>)> = Vec::new();
1327 if !head_empty {
1328 written.push(FlatBlock { attrs: b.attrs.clone(), ..Default::default() });
1329 entries.push((b.attrs.clone(), None));
1330 }
1331 for (j, f) in flat.iter().enumerate().take(hi).skip(lo) {
1332 written.push(f.clone());
1333 let k = if j == 0 { if head_empty { kb } else { l } } else { keeps[j] };
1334 entries.push((f.attrs.clone(), Some(k)));
1335 }
1336 at = m.insert_blocks(at, &written);
1337 let tail_attrs = if merge_last {
1338 let f = &flat[n - 1];
1339 if f.attrs.kind == Leaf::Code {
1340 at = m.insert(at, &f.plain(), &Marks::none());
1341 } else {
1342 at = m.insert_inline(at, &f.inl);
1343 }
1344 let k = if n == 1 && head_empty { kb } else { keeps[n - 1] };
1345 (f.attrs.clone(), Some(k))
1346 } else {
1347 (Attrs { kind: b.kind(), lang: b.attrs.lang.clone(), wrap: b.attrs.wrap.clone(), ..Attrs::default() }, Some(l))
1348 };
1349 entries.push(tail_attrs);
1350 relink(m, b.index, entries, nk);
1351 cx.set_caret(pos::snap(m, at));
1352 true
1353}
1354
1355/// The selected content as blocks. A selection inside one block gives one paragraph
1356/// (pasting it back merges into the target block).
1357pub fn selected_blocks(m: &Model, sel: &Selection) -> Vec<Block> {
1358 if let Selection::Node(p) = *sel {
1359 let b = m.at(p);
1360 if b.kind() == Leaf::Rule {
1361 return vec![Block::Rule];
1362 }
1363 let fb = flat::read_delta(m.slice(p, p + 1));
1364 return vec![Block::Paragraph(fb.into_iter().next().map(|f| f.inl).unwrap_or_default())];
1365 }
1366 let Some((from, to)) = pos::text_range(m, sel) else { return Vec::new() };
1367 let (x, y) = (m.at(from), m.at(to));
1368 if x.index == y.index {
1369 let fb = flat::read_delta(m.slice(from, to));
1370 let inl = fb.into_iter().next().map(|mut f| {
1371 if x.kind() == Leaf::Code {
1372 vec![Inline::Text(f.plain(), Default::default())]
1373 } else {
1374 std::mem::take(&mut f.inl)
1375 }
1376 });
1377 return vec![Block::Paragraph(inl.unwrap_or_default())];
1378 }
1379 let mut blocks = flat::read_delta(m.slice(from, to));
1380 if to > y.start
1381 && let Some(last) = blocks.last_mut()
1382 {
1383 last.attrs = y.attrs.clone();
1384 if last.attrs.kind == Leaf::Code {
1385 let t = last.plain();
1386 last.inl = vec![Inline::Text(t, Default::default())];
1387 }
1388 }
1389 flat::nest(&blocks)
1390}