markdown/edit.rs
1//! Editing a [`Doc`].
2//!
3//! This is the half of a block editor that has nothing to do with gpui: text
4//! goes in and out of a [`Text`], marks move with it, and blocks split, merge
5//! and indent. Keeping it pure is what makes it testable — the guarantee below
6//! is checked over generated edit sequences, not over the handful of cases
7//! anyone thinks to write down.
8//!
9//! **The guarantee is [`crate::serialize`]'s, preserved.** Call
10//! [`Doc::normalize`] and the document round-trips: serialize, parse, and
11//! nothing moves. An editor that can reach a state its own serializer cannot
12//! express is an editor that corrupts the file on save, and no amount of UI
13//! polish recovers from that.
14//!
15//! Normalizing is a *save* step rather than a keystroke step, and deliberately.
16//! Markdown cannot hold a space at the end of a line, but stripping one the
17//! moment it is typed takes it away mid-word — so the model carries it and
18//! sheds it on the way out, which is what every editor that writes markdown
19//! does.
20//!
21//! Marks are **left-sticky**: text typed at the end of a bold run is bold, text
22//! typed at its start is not. The caret inherits formatting from the character
23//! before it, which is what every editor does and what nobody notices until it
24//! is wrong.
25
26use std::ops::Range;
27
28use crate::{
29 doc::{Block, BlockKind, Doc, Mark, MarkSpan, Part, Text},
30 select::{Cursor, Selection},
31};
32
33/// What a [`Doc::replace`] did, for anything holding a position it moved.
34///
35/// The caret is [`Doc::replace`]'s own answer and every caller wants it. The
36/// other two are for a caller keeping a position of its own — a comment anchor,
37/// a bookmark into the document — which has no other way to learn that the text
38/// under it shifted.
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub struct Splice {
41 /// What the call covered, clamped and in document order.
42 pub removed: Selection,
43 /// Where the caret landed: the end of what went in.
44 pub caret: Cursor,
45 /// The change in block count, which every block after [`Self::removed`]
46 /// moves by.
47 pub blocks: isize,
48}
49
50impl Text {
51 /// Insert at a byte offset, moving the marks with it.
52 pub fn insert(&mut self, at: usize, s: &str) {
53 let at = at.min(self.text.len());
54 if s.is_empty() {
55 return;
56 }
57 let n = s.len();
58 self.text.insert_str(at, s);
59 for span in &mut self.marks {
60 if at <= span.range.start {
61 span.range.start += n;
62 span.range.end += n;
63 } else if at <= span.range.end {
64 // Inside, or exactly at the end — the left-sticky rule.
65 span.range.end += n;
66 }
67 }
68 self.normalize_marks();
69 }
70
71 /// Remove a byte range, collapsing any mark that covered it.
72 pub fn remove(&mut self, range: Range<usize>) {
73 let range = self.clamp(range);
74 if range.is_empty() {
75 return;
76 }
77 self.text.replace_range(range.clone(), "");
78 let shift = |offset: usize| {
79 if offset <= range.start {
80 offset
81 } else if offset >= range.end {
82 offset - range.len()
83 } else {
84 range.start
85 }
86 };
87 for span in &mut self.marks {
88 span.range = shift(span.range.start)..shift(span.range.end);
89 }
90 self.normalize_marks();
91 }
92
93 /// Add `mark` over `range`, or take it away if the whole range has it.
94 pub fn toggle(&mut self, range: Range<usize>, mark: Mark) {
95 let range = self.clamp(range);
96 if range.is_empty() {
97 return;
98 }
99 if self.covered_by(&range, &mark) {
100 self.marks = std::mem::take(&mut self.marks)
101 .into_iter()
102 .flat_map(|span| subtract(span, &range, &mark))
103 .collect();
104 } else {
105 self.marks.push(MarkSpan { range, mark });
106 }
107 self.normalize_marks();
108 }
109
110 /// Whether every byte of `range` already carries `mark`.
111 pub fn covered_by(&self, range: &Range<usize>, mark: &Mark) -> bool {
112 !range.is_empty()
113 && self.marks.iter().any(|span| {
114 span.mark == *mark && span.range.start <= range.start && span.range.end >= range.end
115 })
116 }
117
118 /// Cut at `at`, returning the tail. The head keeps this [`Text`].
119 pub fn split_off(&mut self, at: usize) -> Text {
120 let at = at.min(self.text.len());
121 let mut tail = Text {
122 text: self.text.split_off(at),
123 marks: Vec::new(),
124 };
125 let mut head = Vec::new();
126 for span in std::mem::take(&mut self.marks) {
127 if span.range.start < at {
128 head.push(MarkSpan {
129 range: span.range.start..span.range.end.min(at),
130 mark: span.mark.clone(),
131 });
132 }
133 if span.range.end > at {
134 tail.marks.push(MarkSpan {
135 range: span.range.start.saturating_sub(at)..span.range.end - at,
136 mark: span.mark,
137 });
138 }
139 }
140 self.marks = head;
141 self.normalize_marks();
142 tail.normalize_marks();
143 tail
144 }
145
146 /// Append `other`, shifting its marks onto the end of this text.
147 pub fn append(&mut self, other: Text) {
148 let offset = self.text.len();
149 self.text.push_str(&other.text);
150 self.marks
151 .extend(other.marks.into_iter().map(|span| MarkSpan {
152 range: span.range.start + offset..span.range.end + offset,
153 mark: span.mark,
154 }));
155 self.normalize_marks();
156 }
157
158 fn clamp(&self, range: Range<usize>) -> Range<usize> {
159 let start = range.start.min(self.text.len());
160 let end = range.end.clamp(start, self.text.len());
161 start..end
162 }
163
164 /// Drop marks that cover nothing and merge ones that touch.
165 ///
166 /// Both matter to the round trip rather than to tidiness: an empty bold
167 /// span serializes to `****`, which is literal text, and two abutting bold
168 /// spans serialize to `**a****b**`, which is not one bold run.
169 pub(crate) fn normalize_marks(&mut self) {
170 // Emphasis cannot open or close against whitespace — `* t*` is two
171 // literal asterisks, not italic — so a mark reaching over a space has
172 // no spelling that survives a round trip. Shrinking it to the text it
173 // can actually cover is also what a user means when a drag-selection
174 // catches the trailing space.
175 for ix in 0..self.marks.len() {
176 if !matches!(
177 self.marks[ix].mark,
178 Mark::Bold | Mark::Italic | Mark::Strike | Mark::Code
179 ) {
180 continue;
181 }
182 let range = self.marks[ix].range.clone();
183 if range.end > self.text.len() {
184 continue;
185 }
186 let slice = &self.text[range.clone()];
187 let start = range.start + (slice.len() - slice.trim_start().len());
188 let end = (range.end - (slice.len() - slice.trim_end().len())).max(start);
189 self.marks[ix].range = start..end;
190 }
191
192 let len = self.text.len();
193 self.marks.retain(|span| {
194 span.range.end <= len && (!span.range.is_empty() || matches!(span.mark, Mark::Image(_)))
195 });
196
197 // A code span is atomic: nothing can start or stop inside one. A mark
198 // that only half covers it has no spelling, so it grows to take the
199 // whole span — which is also what the markdown for it reads back as.
200 let code: Vec<Range<usize>> = self
201 .marks
202 .iter()
203 .filter(|span| span.mark == Mark::Code)
204 .map(|span| span.range.clone())
205 .collect();
206 for span in &mut self.marks {
207 if span.mark == Mark::Code {
208 continue;
209 }
210 for range in &code {
211 let crosses = span.range.start > range.start && span.range.start < range.end
212 || span.range.end > range.start && span.range.end < range.end;
213 if crosses {
214 span.range.start = span.range.start.min(range.start);
215 span.range.end = span.range.end.max(range.end);
216 }
217 }
218 }
219
220 // Emphasis nests or it is disjoint; it cannot cross. `**a*b**c*` is
221 // not bold-then-italic overlapping, it is a parse error waiting to
222 // happen — so when two spans cross, the one that opened first grows to
223 // contain the other. Growing rather than clipping keeps every mark the
224 // user applied; only its reach changes, and only where markdown left
225 // no alternative.
226 for _ in 0..self.marks.len().max(1) {
227 let mut crossed = false;
228 for a in 0..self.marks.len() {
229 for b in 0..self.marks.len() {
230 let (first, second) = (&self.marks[a].range, &self.marks[b].range);
231 if second.start > first.start
232 && second.start < first.end
233 && second.end > first.end
234 {
235 let end = second.end;
236 self.marks[a].range.end = end;
237 crossed = true;
238 }
239 }
240 }
241 if !crossed {
242 break;
243 }
244 }
245
246 // Two marks that end at the same offset close as two delimiter runs
247 // back to back — `**b**~~`. CommonMark will not let the outer one close
248 // there if a letter follows: a run preceded by punctuation has to be
249 // followed by whitespace or punctuation to be right-flanking, so
250 // `~~a **b**~~c` cannot be written at all. Nudging the outer end past
251 // the word separates the two runs and it can.
252 for _ in 0..self.marks.len().max(1) {
253 let mut nudged = false;
254 for a in 0..self.marks.len() {
255 let end = self.marks[a].range.end;
256 let followed_by_word = self.text[end..]
257 .chars()
258 .next()
259 .is_some_and(char::is_alphanumeric);
260 let shared = self.marks.iter().enumerate().any(|(b, other)| {
261 b != a
262 && other.range.end == end
263 && other.range.start > self.marks[a].range.start
264 });
265 if followed_by_word && shared {
266 let extra = self.text[end..]
267 .find(|c: char| !c.is_alphanumeric())
268 .unwrap_or(self.text.len() - end);
269 self.marks[a].range.end = end + extra;
270 nudged = true;
271 }
272 }
273 if !nudged {
274 break;
275 }
276 }
277
278 let mut ix = 0;
279 while ix < self.marks.len() {
280 let mut merged = None;
281 for other in ix + 1..self.marks.len() {
282 let (a, b) = (&self.marks[ix], &self.marks[other]);
283 if a.mark == b.mark
284 && a.range.start <= b.range.end
285 && b.range.start <= a.range.end
286 && !matches!(a.mark, Mark::Image(_) | Mark::Mention { .. })
287 {
288 merged = Some((
289 other,
290 a.range.start.min(b.range.start),
291 a.range.end.max(b.range.end),
292 ));
293 break;
294 }
295 }
296 match merged {
297 Some((other, start, end)) => {
298 self.marks[ix].range = start..end;
299 self.marks.remove(other);
300 }
301 None => ix += 1,
302 }
303 }
304
305 // Document order, outermost first — the order a parse produces, so an
306 // edited document compares equal to the same document read from disk.
307 // The sort is stable, which is what keeps `**_x_**` and `_**x**_`
308 // apart: their spans are identical and only their order differs.
309 self.marks.sort_by(|a, b| {
310 a.range
311 .start
312 .cmp(&b.range.start)
313 .then(b.range.end.cmp(&a.range.end))
314 });
315 }
316}
317
318/// `span` minus `range`, when they share a mark — zero, one or two pieces.
319fn subtract(span: MarkSpan, range: &Range<usize>, mark: &Mark) -> Vec<MarkSpan> {
320 if span.mark != *mark || span.range.end <= range.start || span.range.start >= range.end {
321 return vec![span];
322 }
323 let mut out = Vec::new();
324 if span.range.start < range.start {
325 out.push(MarkSpan {
326 range: span.range.start..range.start,
327 mark: span.mark.clone(),
328 });
329 }
330 if span.range.end > range.end {
331 out.push(MarkSpan {
332 range: range.end..span.range.end,
333 mark: span.mark,
334 });
335 }
336 out
337}
338
339impl Doc {
340 /// Split block `ix` at byte offset `at`, returning the new block's index.
341 ///
342 /// The tail keeps the block's kind so Enter in a list makes another item —
343 /// except for a heading, where the body that follows a title is body text.
344 pub fn split(&mut self, ix: usize, at: usize) -> usize {
345 if ix >= self.blocks.len() {
346 return ix;
347 }
348 let indent = self.blocks[ix].indent;
349 // Nothing to cut for a block with no body — Enter after an atomic
350 // block opens a paragraph.
351 let tail = self.blocks[ix]
352 .text_at_mut(Part::Body)
353 .map(|text| text.split_off(at))
354 .unwrap_or_default();
355 let kind = match &self.blocks[ix].kind {
356 BlockKind::Bullet(_) => BlockKind::Bullet(tail),
357 BlockKind::Ordered { .. } => BlockKind::Ordered {
358 number: 1,
359 text: tail,
360 },
361 BlockKind::Task { .. } => BlockKind::Task {
362 checked: false,
363 text: tail,
364 },
365 BlockKind::Quote(_) => BlockKind::Quote(tail),
366 // A heading titles what follows it; what follows is body text.
367 _ => BlockKind::Paragraph(tail),
368 };
369 self.blocks.insert(ix + 1, Block::at(kind, indent));
370 self.repair();
371 ix + 1
372 }
373
374 /// Backspace at the start of a block.
375 ///
376 /// Notion's chain, in order: an indented block outdents, an image with
377 /// nothing written under it goes, a block wearing syntax around its text
378 /// gives the syntax up, and only a plain block at the left margin merges
379 /// into the one above it. When that one holds no body there is nothing to
380 /// merge into, so the caret steps into a fence or a table, and a rule —
381 /// which no caret can enter, and so no other key can remove — goes.
382 /// Returns where the caret landed, and `None` when nothing moved.
383 ///
384 /// A table cell is not a position that can swallow its neighbour, so
385 /// backspace at the start of one does nothing rather than eating the table.
386 pub fn merge_back(&mut self, at: Cursor) -> Option<Cursor> {
387 if matches!(at.part, Part::Cell { .. }) {
388 return None;
389 }
390 let block = self.blocks.get(at.block)?;
391 if block.indent > 0 {
392 self.outdent(at.block);
393 return Some(Cursor::new(at.block, at.part, 0));
394 }
395 // A caption is the only handle a caret has on an image, so with the
396 // caption empty there is nothing left to take but the picture.
397 if at.part == Part::Caption && block.text_at(Part::Caption)?.is_empty() {
398 let previous = at.block.checked_sub(1);
399 self.blocks.remove(at.block);
400 self.repair();
401 let Some(previous) = previous else {
402 return Some(Cursor::default().clamp(self));
403 };
404 let part = self.blocks[previous]
405 .parts()
406 .last()
407 .copied()
408 .unwrap_or_default();
409 return Some(Cursor::new(previous, part, 0).end(self));
410 }
411 // Every prefix [`shortcut`] reads is chrome around text; the first
412 // backspace takes the chrome and leaves the text where it was, so what
413 // can be typed in can be typed out.
414 let unwrapped = match &block.kind {
415 kind if is_marker(kind) => block.text_at(Part::Body).cloned(),
416 BlockKind::Heading { text, .. } | BlockKind::Quote(text) => Some(text.clone()),
417 BlockKind::Code { code, .. } => Some(code.clone()),
418 _ => None,
419 };
420 if let Some(text) = unwrapped {
421 self.blocks[at.block].kind = BlockKind::Paragraph(text);
422 self.repair();
423 return Some(Cursor::new(at.block, Part::Body, 0));
424 }
425 if at.block == 0 {
426 return None;
427 }
428 let tail = self.blocks[at.block].text_at(Part::Body)?.clone();
429 let previous = at.block - 1;
430 match self.blocks[previous].parts().last().copied() {
431 // Only two blocks that both hold a body can become one.
432 Some(Part::Body) => {
433 let head = self.blocks[previous].text_at_mut(Part::Body)?;
434 let caret = head.text.len();
435 head.append(tail);
436 self.blocks.remove(at.block);
437 self.repair();
438 Some(Cursor::new(previous, Part::Body, caret))
439 }
440 Some(part) => {
441 let end = self.blocks[previous]
442 .text_at(part)
443 .map_or(0, |text| text.text.len());
444 // Stepping into a fence, a caption or a cell leaves this block
445 // where it is, which is right while it still holds something
446 // and a trap once it does not: nothing above it merges, so a
447 // block left empty here is one backspace can never reach again.
448 if tail.is_empty() {
449 self.blocks.remove(at.block);
450 self.repair();
451 }
452 Some(Cursor::new(previous, part, end))
453 }
454 None => {
455 self.blocks.remove(previous);
456 self.repair();
457 Some(Cursor::new(previous, at.part, at.offset))
458 }
459 }
460 }
461
462 /// Apply an edit to the text at `at`, then put the block back in order.
463 ///
464 /// The editor should reach text through here rather than mutating a block
465 /// directly: a heading or a table cell that acquires a newline has no
466 /// spelling, and nothing else is positioned to notice.
467 pub fn edit_at(&mut self, at: Cursor, edit: impl FnOnce(&mut Text)) {
468 let Some(block) = self.blocks.get_mut(at.block) else {
469 return;
470 };
471 let one_line = matches!(block.kind, BlockKind::Heading { .. })
472 || matches!(at.part, Part::Cell { .. } | Part::Caption);
473 let Some(text) = block.text_at_mut(at.part) else {
474 return;
475 };
476 edit(text);
477 if one_line {
478 crate::parse::collapse_to_one_line(text);
479 }
480 }
481
482 /// The blocks nested under `ix`, `ix` included — what a move, a duplicate
483 /// or a drag carries with it.
484 ///
485 /// A flat list makes this a scan for the next block that is not deeper,
486 /// which is the whole argument for the flat list.
487 pub fn subtree(&self, ix: usize) -> Range<usize> {
488 let Some(base) = self.blocks.get(ix).map(|block| block.indent) else {
489 return ix..ix;
490 };
491 let mut end = ix + 1;
492 while self
493 .blocks
494 .get(end)
495 .is_some_and(|block| block.indent > base)
496 {
497 end += 1;
498 }
499 ix..end
500 }
501
502 /// Move a block and its children to sit before or after their neighbour.
503 ///
504 /// `delta` counts *siblings*, not rows: moving down past a bullet with
505 /// three children clears all four, or a block would land inside the run it
506 /// was trying to step over.
507 pub fn move_block(&mut self, ix: usize, delta: isize) -> Option<usize> {
508 let span = self.subtree(ix);
509 if span.is_empty() {
510 return None;
511 }
512 let to = match delta {
513 ..0 => {
514 // The start of whichever subtree ends where this one begins.
515 (0..span.start)
516 .rev()
517 .find(|&above| self.subtree(above).end == span.start)?
518 }
519 0.. => {
520 let next = self.subtree(span.end);
521 if next.is_empty() {
522 return None;
523 }
524 // Landing after the neighbour means landing where it ends,
525 // less the hole this subtree leaves behind.
526 next.end - span.len()
527 }
528 };
529 let moved: Vec<Block> = self.blocks.drain(span.clone()).collect();
530 self.blocks.splice(to..to, moved);
531 self.repair();
532 Some(to)
533 }
534
535 /// Copy a block and its children in below themselves.
536 pub fn duplicate(&mut self, ix: usize) -> Option<usize> {
537 let span = self.subtree(ix);
538 if span.is_empty() {
539 return None;
540 }
541 let copy: Vec<Block> = self.blocks[span.clone()].to_vec();
542 self.blocks.splice(span.end..span.end, copy);
543 self.repair();
544 Some(span.end)
545 }
546
547 /// Delete a block and its children.
548 pub fn remove_block(&mut self, ix: usize) {
549 let span = self.subtree(ix);
550 if span.is_empty() {
551 return;
552 }
553 self.blocks.drain(span);
554 self.repair();
555 }
556
557 /// Turn block `ix` into `kind`, carrying its text across and keeping its
558 /// indent.
559 ///
560 /// The one operation a typed prefix, the slash menu and the block menu all
561 /// perform, so none of them reaches into a block's kind on its own.
562 pub fn set_kind(&mut self, ix: usize, kind: BlockKind) {
563 let Some(block) = self.blocks.get_mut(ix) else {
564 return;
565 };
566 let text = match &block.kind {
567 // A bookmark's text is the link it shows, so turning one back into
568 // prose hands the URL over instead of an empty block.
569 BlockKind::Bookmark { url, .. } => Text::link(url),
570 BlockKind::Image { alt, .. } => alt.clone(),
571 _ => block.text_at(Part::Body).cloned().unwrap_or_default(),
572 };
573 block.kind = kind;
574 match block.text_at_mut(Part::Body) {
575 Some(body) => *body = text,
576 // The two kinds whose text is not a body. Code is also the one the
577 // marks cannot come with.
578 None => match &mut block.kind {
579 BlockKind::Code { code, .. } => *code = Text::plain(text.text),
580 BlockKind::Image { alt, .. } => *alt = text,
581 _ => {}
582 },
583 }
584 self.repair();
585 }
586
587 /// The tag on a fenced block — what the label shows, what the highlighter
588 /// reads, and what the info string carries. Not [`Doc::set_kind`]'s job:
589 /// that carries a *body* across, and a fence has none to give back.
590 pub fn set_language(&mut self, ix: usize, language: Option<String>) {
591 if let Some(BlockKind::Code { language: tag, .. }) =
592 self.blocks.get_mut(ix).map(|block| &mut block.kind)
593 {
594 *tag = language;
595 }
596 }
597
598 /// Turn what a selection covers into one code block, leaving whatever it
599 /// did not cover as blocks of its own.
600 ///
601 /// The fence is what markdown has for code over more than one line. An
602 /// inline span is not: no CommonMark spelling puts a line break inside
603 /// backticks, so one written that way comes back as a space.
604 ///
605 /// Marks are dropped on the way in, the way [`Doc::set_kind`] drops them
606 /// when it turns a block into a fence — code is literal to its closing
607 /// fence, and nothing in it is markup.
608 pub fn fence(&mut self, selection: Selection) -> Cursor {
609 let lines: Vec<String> = self
610 .spans(selection)
611 .iter()
612 .filter(|(at, _)| at.part == Part::Body)
613 .filter_map(|(at, range)| {
614 let text = self.blocks[at.block].text_at(at.part)?;
615 text.text.get(range.clone()).map(str::to_string)
616 })
617 .collect();
618 if lines.is_empty() {
619 return selection.head.clamp(self);
620 }
621 let code = Text::plain(lines.join("\n"));
622
623 // Cutting the selection leaves the head and the tail it did not cover
624 // joined in one block, with the caret at the seam between them — which
625 // is where the fence goes.
626 let at = self.replace(selection, Text::default()).caret;
627 let tail = self.split(at.block, at.offset);
628 let indent = self.blocks[at.block].indent;
629 self.blocks.insert(
630 tail,
631 Block::at(
632 BlockKind::Code {
633 language: None,
634 code,
635 },
636 indent,
637 ),
638 );
639 // A selection that covered whole blocks leaves nothing on either side,
640 // and an empty paragraph is not what "turn this into code" asked for.
641 let empty = |block: &Block| {
642 block
643 .text_at(Part::Body)
644 .is_some_and(|text| text.text.is_empty())
645 };
646 if self.blocks.get(tail + 1).is_some_and(empty) {
647 self.blocks.remove(tail + 1);
648 }
649 let mut fence = tail;
650 if empty(&self.blocks[at.block]) {
651 self.blocks.remove(at.block);
652 fence -= 1;
653 }
654 self.repair();
655 Cursor::new(fence, Part::Code, 0).clamp(self)
656 }
657
658 /// The way back out of a fence: every line becomes a paragraph. `None` when
659 /// the selection is not all code, which is what makes this the other half
660 /// of a toggle rather than an operation of its own.
661 pub fn unfence(&mut self, selection: Selection) -> Option<Cursor> {
662 let (start, end) = selection.clamp(self).ordered();
663 let blocks = start.block..=end.block;
664 if !blocks
665 .clone()
666 .all(|ix| matches!(self.blocks[ix].kind, BlockKind::Code { .. }))
667 {
668 return None;
669 }
670 for ix in blocks.rev() {
671 let BlockKind::Code { code, .. } = &self.blocks[ix].kind else {
672 continue;
673 };
674 let indent = self.blocks[ix].indent;
675 let paragraphs: Vec<Block> = code
676 .text
677 .split('\n')
678 .map(|line| Block::at(BlockKind::Paragraph(Text::plain(line)), indent))
679 .collect();
680 self.blocks.splice(ix..=ix, paragraphs);
681 }
682 self.repair();
683 Some(Cursor::new(start.block, Part::Body, 0).clamp(self))
684 }
685
686 /// Every text a selection touches, with the slice of it covered.
687 ///
688 /// One selection can reach across paragraphs and table cells, and a mark
689 /// applies to each of them separately — marks live inside a [`Text`] and
690 /// have no way to span two.
691 pub fn spans(&self, selection: Selection) -> Vec<(Cursor, Range<usize>)> {
692 let (start, end) = selection.clamp(self).ordered();
693 let (first, last) = (
694 Cursor::new(start.block, start.part, 0),
695 Cursor::new(end.block, end.part, 0),
696 );
697 let mut out = Vec::new();
698 for block in start.block..=end.block.min(self.blocks.len().saturating_sub(1)) {
699 for part in self.blocks[block].parts() {
700 let here = Cursor::new(block, part, 0);
701 if here < first || here > last {
702 continue;
703 }
704 let len = here.len_in(self).unwrap_or(0);
705 let from = if here == first { start.offset } else { 0 };
706 let to = if here == last { end.offset } else { len };
707 if from < to.min(len) {
708 out.push((here, from..to.min(len)));
709 }
710 }
711 }
712 out
713 }
714
715 /// Add `mark` over a selection, or take it away if every part of the
716 /// selection already carries it.
717 ///
718 /// The decision is made across the whole selection before anything moves:
719 /// dragging over a bold word and a plain one and pressing cmd-B should bold
720 /// the rest rather than unbolding the half that was already there.
721 pub fn toggle_mark(&mut self, selection: Selection, mark: Mark) {
722 let spans = self.spans(selection);
723 let remove = self.covered_by(selection, &mark);
724
725 for (at, range) in spans {
726 // Code is literal to its closing fence and a caption has no room
727 // for markup between its brackets; nothing in either is markup.
728 if matches!(at.part, Part::Code | Part::Caption) {
729 continue;
730 }
731 if remove == self.carries(&at, &range, &mark) {
732 let mark = mark.clone();
733 self.edit_at(at, |text| text.toggle(range, mark));
734 }
735 }
736 }
737
738 /// The marks a selection carries throughout — what a toolbar paints as lit.
739 ///
740 /// Collapsed, it answers with the marks the next character typed here would
741 /// join, which is the **left-sticky** rule [`Text::insert`] already
742 /// follows: the run ending at the caret, never the one starting there.
743 pub fn marks(&self, selection: Selection) -> Vec<Mark> {
744 let mut marks: Vec<Mark> = Vec::new();
745 if selection.is_collapsed() {
746 let at = selection.head.clamp(self);
747 let Some(text) = self.blocks.get(at.block).and_then(|b| b.text_at(at.part)) else {
748 return marks;
749 };
750 for span in &text.marks {
751 if span.range.start < at.offset && at.offset <= span.range.end {
752 marks.push(span.mark.clone());
753 }
754 }
755 marks.dedup();
756 return marks;
757 }
758 for (at, range) in self.spans(selection) {
759 let Some(text) = self.blocks[at.block].text_at(at.part) else {
760 continue;
761 };
762 for span in &text.marks {
763 if span.range.start < range.end
764 && span.range.end > range.start
765 && !marks.contains(&span.mark)
766 {
767 marks.push(span.mark.clone());
768 }
769 }
770 }
771 marks.retain(|mark| self.covered_by(selection, mark));
772 marks
773 }
774
775 /// Whether every part of a selection already carries `mark` — what decides
776 /// between adding it and taking it away, and what a toolbar button reads to
777 /// know whether it is lit.
778 pub fn covered_by(&self, selection: Selection, mark: &Mark) -> bool {
779 let spans = self.spans(selection);
780 !spans.is_empty()
781 && spans.iter().all(|(at, range)| {
782 matches!(at.part, Part::Code | Part::Caption) || self.carries(at, range, mark)
783 })
784 }
785
786 fn carries(&self, at: &Cursor, range: &Range<usize>, mark: &Mark) -> bool {
787 self.blocks[at.block]
788 .text_at(at.part)
789 .is_some_and(|text| text.covered_by(range, mark))
790 }
791
792 /// The sub-document a selection covers — what a copy puts on the clipboard.
793 ///
794 /// A table is atomic here for the same reason it is in [`Doc::replace`]:
795 /// half a table has no shape worth keeping, so a selection reaching into
796 /// one takes it whole.
797 pub fn slice(&self, selection: Selection) -> Doc {
798 let (start, end) = selection.clamp(self).ordered();
799 let mut out = Doc {
800 blocks: self.blocks[start.block..=end.block].to_vec(),
801 };
802 let last = end.block - start.block;
803 // Tail first: trimming the head would move the offsets the tail is in.
804 if !matches!(end.part, Part::Cell { .. })
805 && let Some(text) = out.blocks[last].text_at_mut(end.part)
806 {
807 text.split_off(end.offset);
808 }
809 if !matches!(start.part, Part::Cell { .. })
810 && let Some(text) = out.blocks[0].text_at_mut(start.part)
811 {
812 *text = text.split_off(start.offset);
813 }
814 // The slice starts at the left margin whatever depth it was cut from.
815 out.repair();
816 out
817 }
818
819 /// Replace a selection with a whole document — the paste path.
820 ///
821 /// A lone paragraph goes in as inline text, marks and all: pasting a
822 /// sentence into a sentence must not make a new block. Anything else
823 /// arrives as blocks, and the remainder of the caret's block follows them.
824 pub fn splice(&mut self, selection: Selection, other: Doc) -> Cursor {
825 let blocks = other.blocks;
826 let inline = match blocks.as_slice() {
827 [] => Some(Text::default()),
828 [block] => match &block.kind {
829 BlockKind::Paragraph(text) => Some(text.clone()),
830 _ => None,
831 },
832 _ => None,
833 };
834 if let Some(text) = inline {
835 return self.replace(selection, text).caret;
836 }
837
838 let caret = self.replace(selection, Text::default()).caret;
839 let base = self.blocks[caret.block].indent;
840 // Split so what followed the caret follows the paste too. An empty
841 // remainder is the blank block a paste at the end would leave behind.
842 let tail = self.split(caret.block, caret.offset);
843 let empty_tail = self.blocks[tail]
844 .text_at(Part::Body)
845 .is_some_and(Text::is_empty);
846
847 let mut at = caret.block;
848 for block in blocks {
849 at += 1;
850 self.blocks
851 .insert(at, Block::at(block.kind, base.saturating_add(block.indent)));
852 }
853 if empty_tail {
854 self.blocks.remove(at + 1);
855 }
856 // And the block the caret opened in, if the paste displaced all of it.
857 let head_empty = self.blocks[caret.block]
858 .text_at(Part::Body)
859 .is_some_and(Text::is_empty);
860 if head_empty && matches!(self.blocks[caret.block].kind, BlockKind::Paragraph(_)) {
861 self.blocks.remove(caret.block);
862 at -= 1;
863 }
864 self.repair();
865 Cursor::new(at, Part::Body, 0).end(self).clamp(self)
866 }
867
868 /// Replace everything a selection covers with `text`, and say where the
869 /// caret lands.
870 ///
871 /// **The one mutation.** Typing, backspace, delete, cut and paste are all
872 /// this call with a different argument, which is why none of them needs to
873 /// know whether a selection was empty, spanned two paragraphs, or swallowed
874 /// a table on the way past.
875 pub fn replace(&mut self, selection: Selection, text: Text) -> Splice {
876 // An empty document has no block to put anything in; editing one opens
877 // the paragraph every other path then assumes exists.
878 if self.blocks.is_empty() {
879 self.blocks
880 .push(Block::new(BlockKind::Paragraph(Text::default())));
881 }
882 // Counted after that, so the block a nothing-document opens with is not
883 // a shift anything downstream has to hear about.
884 let before = self.blocks.len();
885 let (start, end) = selection.clamp(self).ordered();
886 let removed = Selection::new(start, end);
887
888 // Code is literal and a caption is written between brackets, so marks
889 // arriving from a paste have nowhere to go in either.
890 let text = if matches!(start.part, Part::Code | Part::Caption) {
891 Text::plain(text.text)
892 } else {
893 text
894 };
895
896 if start.block == end.block && start.part == end.part {
897 let at = start.offset + text.text.len();
898 self.edit_at(start, |body| {
899 body.remove(start.offset..end.offset);
900 body.insert(start.offset, &text.text);
901 for span in &text.marks {
902 body.marks.push(MarkSpan {
903 range: start.offset + span.range.start..start.offset + span.range.end,
904 mark: span.mark.clone(),
905 });
906 }
907 body.normalize_marks();
908 });
909 return Splice {
910 removed,
911 caret: Cursor {
912 offset: at,
913 ..start
914 }
915 .clamp(self),
916 blocks: 0,
917 };
918 }
919
920 // Across cells of one table the table itself survives: the covered
921 // cells are emptied and the shape stays, which is what a spreadsheet
922 // selection does and what keeps the columns from collapsing.
923 if start.block == end.block {
924 for part in self.blocks[start.block].parts() {
925 if part < start.part || part > end.part {
926 continue;
927 }
928 // `remove` clamps, so the open end needs no length.
929 let (from, to) = (
930 if part == start.part { start.offset } else { 0 },
931 if part == end.part {
932 end.offset
933 } else {
934 usize::MAX
935 },
936 );
937 self.edit_at(Cursor::new(start.block, part, 0), |body| {
938 body.remove(from..to)
939 });
940 }
941 // The recursion is the insert alone, so what it covered is not what
942 // this call covered — only the caret comes back out of it.
943 let caret = self.replace(Selection::at(start), text).caret;
944 return Splice {
945 removed,
946 caret,
947 blocks: self.blocks.len() as isize - before as isize,
948 };
949 }
950
951 // Across blocks the head keeps its kind and takes the tail's
952 // remainder, and everything between them goes.
953 //
954 // A **table is atomic** to a selection that leaves it. Half a table has
955 // no shape worth keeping, so an end landing in one takes the whole
956 // block rather than splicing a lone cell into a paragraph.
957 let head_keeps = !matches!(start.part, Part::Cell { .. })
958 && self.blocks[start.block].text_at(start.part).is_some();
959 let tail = match end.part {
960 Part::Cell { .. } => Text::default(),
961 part => self.blocks[end.block]
962 .text_at_mut(part)
963 .map(|body| body.split_off(end.offset))
964 .unwrap_or_default(),
965 };
966
967 let indent = self.blocks[start.block].indent;
968 let first = if head_keeps {
969 start.block + 1
970 } else {
971 start.block
972 };
973 self.blocks.drain(first..=end.block);
974
975 let caret = if head_keeps {
976 self.edit_at(start, |body| body.remove(start.offset..usize::MAX));
977 self.edit_at(start, |body| body.append(tail));
978 start
979 } else {
980 // Everything the selection touched is gone, so the tail arrives as
981 // a paragraph in its place.
982 self.blocks
983 .insert(start.block, Block::at(BlockKind::Paragraph(tail), indent));
984 Cursor::new(start.block, Part::Body, 0)
985 };
986 self.repair();
987 let caret = caret.clamp(self);
988 let caret = self.replace(Selection::at(caret), text).caret;
989 Splice {
990 removed,
991 caret,
992 blocks: self.blocks.len() as isize - before as isize,
993 }
994 }
995
996 /// Put the document into the form markdown can hold — the save step.
997 ///
998 /// Drops the whitespace markdown discards anyway (leading and trailing on
999 /// every line, blank lines at a block's edges), flattens the blocks whose
1000 /// output is one line, and renumbers ordered runs. After this,
1001 /// `parse(serialize(doc)) == doc`.
1002 pub fn normalize(&mut self) {
1003 self.normalize_with(&crate::Marks::default());
1004 }
1005
1006 /// [`Doc::normalize`] with the app's own marks — see [`crate::Marks`].
1007 pub fn normalize_with(&mut self, marks: &crate::Marks) {
1008 for block in &mut self.blocks {
1009 let one_line = matches!(block.kind, BlockKind::Heading { .. });
1010 match &mut block.kind {
1011 BlockKind::Paragraph(text)
1012 | BlockKind::Heading { text, .. }
1013 | BlockKind::Bullet(text)
1014 | BlockKind::Ordered { text, .. }
1015 | BlockKind::Task { text, .. }
1016 | BlockKind::Quote(text) => {
1017 *text = crate::parse::normalize(&text.text, &text.marks);
1018 text.normalize_marks();
1019 if one_line {
1020 crate::parse::collapse_to_one_line(text);
1021 }
1022 }
1023 BlockKind::Table { header, rows, .. } => {
1024 for cell in header.iter_mut().chain(rows.iter_mut().flatten()) {
1025 *cell = crate::parse::normalize(&cell.text, &cell.marks);
1026 cell.normalize_marks();
1027 crate::parse::collapse_to_one_line(cell);
1028 }
1029 }
1030 // A caption lives between brackets, where a line break has no
1031 // spelling at all.
1032 BlockKind::Image { alt, .. } => crate::parse::collapse_to_one_line(alt),
1033 BlockKind::Code { .. } | BlockKind::Bookmark { .. } | BlockKind::Rule => {}
1034 }
1035 }
1036 // A blank paragraph is the empty line an editor leaves behind, and
1037 // markdown has no way to write one down — blank lines there separate
1038 // blocks rather than being one. An empty heading or list item is
1039 // different: `# ` and `- ` are both real, so those stay.
1040 self.blocks.retain(|block| {
1041 !matches!(
1042 &block.kind,
1043 BlockKind::Paragraph(text) | BlockKind::Quote(text) if text.is_empty()
1044 )
1045 });
1046 self.repair();
1047
1048 // The rules above keep every ordinary edit lossless. They cannot be
1049 // complete, and no serializer fix would make them so: whether a mark
1050 // boundary can be written depends on CommonMark's flanking rules, and
1051 // some marks have no spelling at all. Bold ending on a `~` with a letter
1052 // after it is one — a closing delimiter preceded by punctuation and
1053 // followed by a letter is not right-flanking, so `Tit**l\~\~**e` does
1054 // not close. That is a limit of the format, not a bug in the writer.
1055 //
1056 // So the last word goes to markdown: adopt the document it can hold.
1057 //
1058 // This is exact rather than approximate. Anything [`crate::parse`]
1059 // returns is a fixed point of the round trip — that is the guarantee the
1060 // parser is tested for — so writing this document out and reading it
1061 // back yields one by construction. Marks with no spelling are dropped
1062 // here, in front of the reader, rather than silently at save time.
1063 //
1064 // The cheaper rules above still earn their place: they are what keeps
1065 // the ordinary edit lossless, so this step has nothing left to take.
1066 *self = crate::parse_with(&crate::serialize_with(self, marks), marks);
1067 }
1068
1069 /// Tab. A block can go one level deeper than the one above it, and its
1070 /// children come with it.
1071 pub fn indent(&mut self, ix: usize) -> bool {
1072 let Some(block) = self.blocks.get(ix) else {
1073 return false;
1074 };
1075 if block.indent >= self.ceiling(ix) {
1076 return false;
1077 }
1078 self.shift_subtree(ix, 1);
1079 // A run that has just been nested has nothing above it to carry on
1080 // from, so it starts over. `renumber` cannot decide this on its own: a
1081 // list written `5.` keeps its 5, and from the numbers alone the two
1082 // cases look the same.
1083 if self.begins_run(ix)
1084 && let BlockKind::Ordered { number, .. } = &mut self.blocks[ix].kind
1085 {
1086 *number = 1;
1087 }
1088 self.repair();
1089 true
1090 }
1091
1092 /// Whether the block at `ix` starts a run of ordered items rather than
1093 /// carrying one on: the nearest block at its own indent, before the list
1094 /// it sits in ends, is not an ordered item.
1095 fn begins_run(&self, ix: usize) -> bool {
1096 let indent = self.blocks[ix].indent;
1097 self.blocks[..ix]
1098 .iter()
1099 .rev()
1100 .take_while(|block| block.indent >= indent)
1101 .find(|block| block.indent == indent)
1102 .is_none_or(|block| !matches!(block.kind, BlockKind::Ordered { .. }))
1103 }
1104
1105 /// How deep block `ix` is allowed to sit.
1106 ///
1107 /// Markdown expresses nesting through list items and nothing else, so a
1108 /// block may only go deeper than the one above it when that one is a
1109 /// marker. Indenting a paragraph under a *heading* would serialize to four
1110 /// leading spaces, which reads back as an indented code block.
1111 pub fn ceiling(&self, ix: usize) -> u8 {
1112 match ix.checked_sub(1).map(|previous| &self.blocks[previous]) {
1113 None => 0,
1114 Some(previous) if is_marker(&previous.kind) => previous.indent + 1,
1115 Some(previous) => previous.indent,
1116 }
1117 }
1118
1119 /// Clamp every indent to what the document can actually express, then make
1120 /// ordered runs consecutive. Cheap, total, and called after anything
1121 /// structural — a local rule is not enough, because outdenting one block
1122 /// can leave the block *after* it stranded a level too deep.
1123 ///
1124 /// Public because an editor that changes a block's *kind* has to restore
1125 /// the invariant too, and only this knows what it is.
1126 pub fn repair(&mut self) {
1127 for ix in 0..self.blocks.len() {
1128 let ceiling = self.ceiling(ix);
1129 self.blocks[ix].indent = self.blocks[ix].indent.min(ceiling);
1130 }
1131 self.renumber();
1132 }
1133
1134 /// Shift-Tab, children included.
1135 pub fn outdent(&mut self, ix: usize) -> bool {
1136 if self.blocks.get(ix).is_none_or(|block| block.indent == 0) {
1137 return false;
1138 }
1139 self.shift_subtree(ix, -1);
1140 self.repair();
1141 true
1142 }
1143
1144 /// Move a block and everything nested under it. Children have to travel
1145 /// with the parent or the document invariant breaks the moment a level
1146 /// disappears from under them.
1147 fn shift_subtree(&mut self, ix: usize, by: i8) {
1148 let span = self.subtree(ix);
1149 for block in &mut self.blocks[span] {
1150 block.indent = block.indent.saturating_add_signed(by);
1151 }
1152 }
1153}
1154
1155fn is_marker(kind: &BlockKind) -> bool {
1156 matches!(
1157 kind,
1158 BlockKind::Bullet(_) | BlockKind::Ordered { .. } | BlockKind::Task { .. }
1159 )
1160}
1161
1162/// A markdown prefix typed at the start of a block, and what it turns it into.
1163#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1164pub enum Shortcut {
1165 Heading(u8),
1166 Bullet,
1167 Ordered,
1168 Task(bool),
1169 Quote,
1170 Code,
1171 Rule,
1172}
1173
1174impl Shortcut {
1175 /// The block this shortcut makes, carrying whatever text was left over.
1176 pub fn apply(self, text: Text) -> BlockKind {
1177 match self {
1178 Self::Heading(level) => BlockKind::Heading { level, text },
1179 Self::Bullet => BlockKind::Bullet(text),
1180 Self::Ordered => BlockKind::Ordered { number: 1, text },
1181 Self::Task(checked) => BlockKind::Task { checked, text },
1182 Self::Quote => BlockKind::Quote(text),
1183 // Code is literal, so whatever marks the text carried have no
1184 // meaning inside the fence.
1185 Self::Code => BlockKind::Code {
1186 language: None,
1187 code: Text::plain(text.text),
1188 },
1189 Self::Rule => BlockKind::Rule,
1190 }
1191 }
1192}
1193
1194/// Match a markdown prefix at the start of a block, returning it and how many
1195/// bytes it occupied.
1196///
1197/// This is the input side of the same vocabulary [`crate::parse`] reads: typing
1198/// `## ` makes a heading because pasting `## ` would have. Order matters — a
1199/// task marker is a bullet with more on the end.
1200pub fn shortcut(text: &str) -> Option<(Shortcut, usize)> {
1201 const PREFIXES: &[(&str, Shortcut)] = &[
1202 ("- [ ] ", Shortcut::Task(false)),
1203 ("- [x] ", Shortcut::Task(true)),
1204 ("###### ", Shortcut::Heading(6)),
1205 ("##### ", Shortcut::Heading(5)),
1206 ("#### ", Shortcut::Heading(4)),
1207 ("### ", Shortcut::Heading(3)),
1208 ("## ", Shortcut::Heading(2)),
1209 ("# ", Shortcut::Heading(1)),
1210 ("- ", Shortcut::Bullet),
1211 ("* ", Shortcut::Bullet),
1212 ("+ ", Shortcut::Bullet),
1213 ("1. ", Shortcut::Ordered),
1214 ("> ", Shortcut::Quote),
1215 ("```", Shortcut::Code),
1216 ("---", Shortcut::Rule),
1217 ];
1218 PREFIXES
1219 .iter()
1220 .find(|(prefix, _)| text.starts_with(prefix))
1221 .map(|(prefix, shortcut)| (*shortcut, prefix.len()))
1222}
1223
1224/// A closing inline delimiter just typed, and the run it closes.
1225///
1226/// The inline half of the same vocabulary [`shortcut`] covers: typing the last
1227/// `*` of `**bold**` makes it bold because pasting `**bold**` would have.
1228/// Returns the opening delimiter's range and the text between it and the caret;
1229/// the closing delimiter is `inner.end..caret`.
1230pub fn inline_rule(text: &str, caret: usize) -> Option<(Range<usize>, Range<usize>, Mark)> {
1231 let head = text.get(..caret)?;
1232 // Longest first — `**` is bold, and only what is left of it is italic.
1233 for (delimiter, mark) in [
1234 ("**", Mark::Bold),
1235 ("~~", Mark::Strike),
1236 ("`", Mark::Code),
1237 ("_", Mark::Italic),
1238 ("*", Mark::Italic),
1239 ] {
1240 let Some(closes) = head.strip_suffix(delimiter) else {
1241 continue;
1242 };
1243 let Some(open) = closes.rfind(delimiter) else {
1244 continue;
1245 };
1246 let inner = open + delimiter.len()..closes.len();
1247 let Some(body) = text.get(inner.clone()).filter(|body| !body.is_empty()) else {
1248 continue;
1249 };
1250 // Emphasis cannot open or close against whitespace, so a mark reaching
1251 // over one has no spelling and [`Text::normalize_marks`] would shrink
1252 // it straight back off. A rule that fires and vanishes is worse than
1253 // one that does not fire.
1254 if body.starts_with(char::is_whitespace) || body.ends_with(char::is_whitespace) {
1255 continue;
1256 }
1257 // An underscore inside a word is not emphasis in CommonMark, which is
1258 // the only reason `snake_case_names` survive being typed.
1259 if delimiter == "_"
1260 && text[..open]
1261 .chars()
1262 .next_back()
1263 .is_some_and(char::is_alphanumeric)
1264 {
1265 continue;
1266 }
1267 return Some((open..open + delimiter.len(), inner, mark));
1268 }
1269 None
1270}