BlueGit

ict rusty-teams

Files

rusty-teams / crates / core / src / draft.rs

draft.rs

62bd9112 History
draft.rs 73.0 KiB Download Raw
1use std::ops::Range;
2use std::sync::LazyLock;
3
4use regex::Regex;
5use serde::{Deserialize, Serialize};
6
7use crate::markdown::escape_html;
8use crate::spans::Span;
9
10pub const MAX_DEPTH: u8 = 2;
11const BULLETS: [&str; 3] = ["•", "◦", "▪"];
12const PASTED_BULLETS: [&str; 6] = ["- ", "* ", "+ ", "• ", "◦ ", "▪ "];
13const INDENT: &str = "\u{2003}\u{2003}";
14const QUOTE_MARKER: &str = "\u{2003}";
15const FENCE: &str = "```";
16const MARKDOWN_INDENT: usize = 2;
17
18static TYPED_LINK: LazyLock<Regex> =
19 LazyLock::new(|| Regex::new(r"\[([^\]\n]+)\]\(([^)\s]+)\)$").unwrap());
20static LINK_AT: LazyLock<Regex> =
21 LazyLock::new(|| Regex::new(r"^\[([^\]\n]+)\]\(([^)\s]+)\)").unwrap());
22
23#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
24pub enum MarkKind {
25 Link(String),
26 Bold,
27 Italic,
28 Underline,
29 Strike,
30 Code,
31}
32
33impl MarkKind {
34 pub fn same_format(&self, other: &MarkKind) -> bool {
35 std::mem::discriminant(self) == std::mem::discriminant(other)
36 }
37
38 fn continues_at_end(&self) -> bool {
39 matches!(
40 self,
41 MarkKind::Bold | MarkKind::Italic | MarkKind::Underline | MarkKind::Strike
42 )
43 }
44
45 fn open_tag(&self) -> String {
46 match self {
47 MarkKind::Link(url) => format!("<a href=\"{}\">", escape_html(url)),
48 MarkKind::Bold => "<b>".to_owned(),
49 MarkKind::Italic => "<i>".to_owned(),
50 MarkKind::Underline => "<u>".to_owned(),
51 MarkKind::Strike => "<s>".to_owned(),
52 MarkKind::Code => "<code>".to_owned(),
53 }
54 }
55
56 fn close_tag(&self) -> &'static str {
57 match self {
58 MarkKind::Link(_) => "</a>",
59 MarkKind::Bold => "</b>",
60 MarkKind::Italic => "</i>",
61 MarkKind::Underline => "</u>",
62 MarkKind::Strike => "</s>",
63 MarkKind::Code => "</code>",
64 }
65 }
66}
67
68#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
69pub struct Mark {
70 pub range: Range<usize>,
71 pub kind: MarkKind,
72}
73
74#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
75pub enum LineKind {
76 Text,
77 Bullet(u8),
78 Numbered(u8),
79 Quote,
80 Code(Option<String>),
81}
82
83impl LineKind {
84 pub fn is_list(&self) -> bool {
85 matches!(self, LineKind::Bullet(_) | LineKind::Numbered(_))
86 }
87
88 pub fn depth(&self) -> u8 {
89 match self {
90 LineKind::Bullet(depth) | LineKind::Numbered(depth) => *depth,
91 _ => 0,
92 }
93 }
94
95 pub fn same_format(&self, other: &LineKind) -> bool {
96 std::mem::discriminant(self) == std::mem::discriminant(other)
97 }
98
99 fn with_depth(&self, depth: u8) -> LineKind {
100 match self {
101 LineKind::Bullet(_) => LineKind::Bullet(depth),
102 LineKind::Numbered(_) => LineKind::Numbered(depth),
103 other => other.clone(),
104 }
105 }
106}
107
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109pub enum FormatState {
110 Off,
111 Mixed,
112 On,
113}
114
115/// Formats switched on or off for text typed at `at` before any is typed.
116#[derive(Debug, Clone, Default, PartialEq, Eq)]
117pub struct TypingStyle {
118 pub at: usize,
119 pub add: Vec<MarkKind>,
120 pub remove: Vec<MarkKind>,
121}
122
123impl TypingStyle {
124 pub fn apply(&self, mut kinds: Vec<MarkKind>) -> Vec<MarkKind> {
125 kinds.retain(|kind| !self.remove.iter().any(|removed| removed.same_format(kind)));
126 for added in &self.add {
127 if !kinds.iter().any(|kind| kind.same_format(added)) {
128 kinds.push(added.clone());
129 }
130 }
131 kinds
132 }
133
134 pub fn toggle(&mut self, kind: MarkKind, active: &[MarkKind]) {
135 let is_active = self
136 .apply(active.to_vec())
137 .iter()
138 .any(|existing| existing.same_format(&kind));
139 self.add.retain(|added| !added.same_format(&kind));
140 self.remove.retain(|removed| !removed.same_format(&kind));
141 let inherited = active.iter().any(|existing| existing.same_format(&kind));
142 match (is_active, inherited) {
143 (true, true) => self.remove.push(kind),
144 (false, false) => self.add.push(kind),
145 _ => {}
146 }
147 }
148
149 pub fn is_empty(&self) -> bool {
150 self.add.is_empty() && self.remove.is_empty()
151 }
152}
153
154/// One line without its marker: what the clipboard and `from_lines` carry.
155#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
156pub struct DraftLine {
157 pub kind: LineKind,
158 pub number: Option<u32>,
159 pub content: String,
160 pub marks: Vec<Mark>,
161}
162
163impl DraftLine {
164 fn text(content: &str) -> DraftLine {
165 DraftLine {
166 kind: LineKind::Text,
167 number: None,
168 content: content.to_owned(),
169 marks: Vec::new(),
170 }
171 }
172
173 fn trim_start(&mut self) {
174 let cut = self.content.len() - self.content.trim_start().len();
175 self.content.drain(..cut);
176 for mark in &mut self.marks {
177 mark.range = mark.range.start.saturating_sub(cut)..mark.range.end.saturating_sub(cut);
178 }
179 self.marks.retain(|mark| !mark.range.is_empty());
180 }
181
182 fn trim_end(&mut self) {
183 let length = self.content.trim_end().len();
184 self.content.truncate(length);
185 for mark in &mut self.marks {
186 mark.range = mark.range.start.min(length)..mark.range.end.min(length);
187 }
188 self.marks.retain(|mark| !mark.range.is_empty());
189 }
190}
191
192pub type Edit = (Range<usize>, String);
193
194/// Edits since the last `take_edits`, as disjoint ranges of the text at that point.
195#[derive(Debug, Clone, Default)]
196struct Journal(Vec<Edit>);
197
198impl PartialEq for Journal {
199 fn eq(&self, _: &Journal) -> bool {
200 true
201 }
202}
203
204impl Eq for Journal {}
205
206impl Journal {
207 fn record(&mut self, range: Range<usize>, inserted: usize, text: &str) {
208 if range.is_empty() && inserted == 0 {
209 return;
210 }
211 let mut delta = 0isize;
212 let mut delta_before = 0isize;
213 let mut position = self.0.len();
214 let mut touching: Vec<(usize, usize, usize)> = Vec::new();
215 for (index, (original, replacement)) in self.0.iter().enumerate() {
216 let current_start = (original.start as isize + delta) as usize;
217 let current_end = current_start + replacement.len();
218 if current_end < range.start {
219 delta += replacement.len() as isize - original.len() as isize;
220 delta_before = delta;
221 continue;
222 }
223 if current_start > range.end {
224 position = position.min(index);
225 break;
226 }
227 position = position.min(index);
228 touching.push((index, current_start, current_end));
229 delta += replacement.len() as isize - original.len() as isize;
230 }
231 let original_start = match touching.first() {
232 Some(&(index, current_start, _)) if current_start <= range.start => {
233 self.0[index].0.start
234 }
235 _ => (range.start as isize - delta_before) as usize,
236 };
237 let original_end = match touching.last() {
238 Some(&(index, _, current_end)) if current_end >= range.end => self.0[index].0.end,
239 _ => (range.end as isize - delta) as usize,
240 };
241 let merged_start = touching
242 .first()
243 .map_or(range.start, |&(_, current_start, _)| {
244 current_start.min(range.start)
245 });
246 let merged_end = touching
247 .last()
248 .map_or(range.end, |&(_, _, current_end)| current_end.max(range.end));
249 let merged_end_after = merged_end + inserted - range.len();
250 let replacement = text[merged_start..merged_end_after].to_owned();
251 if let (Some(&(first, ..)), Some(&(last, ..))) = (touching.first(), touching.last()) {
252 self.0.drain(first..=last);
253 }
254 self.0
255 .insert(position, (original_start..original_end, replacement));
256 }
257}
258
259/// Where `offset` of the text before `edits` ends up; an insertion at it pushes it along.
260pub fn map_offset(edits: &[Edit], offset: usize) -> usize {
261 let mut delta = 0isize;
262 for (original, replacement) in edits {
263 if offset >= original.end {
264 delta += replacement.len() as isize - original.len() as isize;
265 } else if offset > original.start {
266 return (original.start as isize + delta) as usize + replacement.len();
267 } else {
268 break;
269 }
270 }
271 (offset as isize + delta) as usize
272}
273
274/// The edits that turn the text after `edits` back into `before`.
275pub fn reverse_edits(edits: &[Edit], before: &str) -> Vec<Edit> {
276 let mut delta = 0isize;
277 edits
278 .iter()
279 .map(|(original, replacement)| {
280 let start = (original.start as isize + delta) as usize;
281 delta += replacement.len() as isize - original.len() as isize;
282 (
283 start..start + replacement.len(),
284 before[original.clone()].to_owned(),
285 )
286 })
287 .collect()
288}
289
290/// Composer text plus formatting. List and quote lines carry their marker in `text`.
291#[derive(Debug, Clone, PartialEq, Eq)]
292pub struct Draft {
293 text: String,
294 marks: Vec<Mark>,
295 lines: Vec<LineKind>,
296 journal: Journal,
297}
298
299impl Default for Draft {
300 fn default() -> Self {
301 Draft::plain("")
302 }
303}
304
305impl Draft {
306 pub fn plain(text: &str) -> Draft {
307 Draft {
308 text: text.to_owned(),
309 marks: Vec::new(),
310 lines: vec![LineKind::Text; text.matches('\n').count() + 1],
311 journal: Journal::default(),
312 }
313 }
314
315 pub fn from_lines(lines: &[DraftLine]) -> Draft {
316 let mut draft = Draft::plain("");
317 draft.insert_lines(0..0, lines);
318 draft.journal = Journal::default();
319 draft
320 }
321
322 pub fn from_markdown(text: &str) -> Draft {
323 Draft::from_lines(&markdown_lines(text))
324 }
325
326 pub fn from_spans(spans: &[Span]) -> Draft {
327 let mut builder = SpanLines::default();
328 builder.walk(spans, &LineKind::Text, &[]);
329 Draft::from_lines(&builder.finish())
330 }
331
332 pub fn text(&self) -> &str {
333 &self.text
334 }
335
336 pub fn marks(&self) -> &[Mark] {
337 &self.marks
338 }
339
340 pub fn lines(&self) -> &[LineKind] {
341 &self.lines
342 }
343
344 pub fn take_edits(&mut self) -> Vec<Edit> {
345 std::mem::take(&mut self.journal.0)
346 }
347
348 pub fn is_blank(&self) -> bool {
349 self.plain_text().trim().is_empty()
350 }
351
352 /// The text without list and quote markers.
353 pub fn plain_text(&self) -> String {
354 self.slice(0..self.text.len())
355 .into_iter()
356 .map(|line| line.content)
357 .collect::<Vec<_>>()
358 .join("\n")
359 }
360
361 pub fn line_ranges(&self) -> Vec<Range<usize>> {
362 let mut ranges = Vec::with_capacity(self.lines.len());
363 let mut start = 0;
364 for (index, _) in self.text.match_indices('\n') {
365 ranges.push(start..index);
366 start = index + 1;
367 }
368 ranges.push(start..self.text.len());
369 ranges
370 }
371
372 pub fn line_at(&self, offset: usize) -> usize {
373 let offset = offset.min(self.text.len());
374 self.text.as_bytes()[..offset]
375 .iter()
376 .filter(|byte| **byte == b'\n')
377 .count()
378 }
379
380 pub fn marker_range(&self, index: usize) -> Range<usize> {
381 let line = self.line_ranges()[index].clone();
382 let length = marker_len(&self.lines[index], &self.text[line.clone()]);
383 line.start..line.start + length
384 }
385
386 pub fn content_range(&self, index: usize) -> Range<usize> {
387 let line = self.line_ranges()[index].clone();
388 self.marker_range(index).end..line.end
389 }
390
391 /// Formats that text typed at `offset` takes on.
392 pub fn style_at(&self, offset: usize) -> Vec<MarkKind> {
393 self.style_for_insertion(offset, offset)
394 }
395
396 pub fn state(&self, range: Range<usize>, kind: &MarkKind) -> FormatState {
397 let parts = self.content_parts(range);
398 let total: usize = parts.iter().map(|part| part.len()).sum();
399 if total == 0 {
400 return FormatState::Off;
401 }
402 let covered: usize = parts
403 .iter()
404 .map(|part| {
405 let mut ranges: Vec<Range<usize>> = self
406 .marks
407 .iter()
408 .filter(|mark| mark.kind.same_format(kind))
409 .map(|mark| mark.range.start.max(part.start)..mark.range.end.min(part.end))
410 .filter(|range| !range.is_empty())
411 .collect();
412 ranges.sort_by_key(|range| range.start);
413 let mut end = part.start;
414 let mut sum = 0;
415 for range in ranges {
416 let start = range.start.max(end);
417 if range.end > start {
418 sum += range.end - start;
419 end = range.end;
420 }
421 }
422 sum
423 })
424 .sum();
425 match covered {
426 0 => FormatState::Off,
427 covered if covered >= total => FormatState::On,
428 _ => FormatState::Mixed,
429 }
430 }
431
432 pub fn line_state(&self, range: Range<usize>, kind: &LineKind) -> FormatState {
433 let lines = self.line_at(range.start)..=self.line_at(range.end);
434 let count = lines.clone().count();
435 let matching = lines
436 .filter(|index| self.lines[*index].same_format(kind))
437 .count();
438 match matching {
439 0 => FormatState::Off,
440 matching if matching == count => FormatState::On,
441 _ => FormatState::Mixed,
442 }
443 }
444
445 pub fn link_in(&self, range: Range<usize>) -> Option<String> {
446 self.marks.iter().find_map(|mark| match &mark.kind {
447 MarkKind::Link(url)
448 if mark.range.start < range.end.max(range.start + 1)
449 && range.start < mark.range.end =>
450 {
451 Some(url.clone())
452 }
453 _ => None,
454 })
455 }
456
457 /// Mixed or off: the whole range gets `kind`. On: it loses it.
458 pub fn toggle(&mut self, range: Range<usize>, kind: MarkKind) {
459 self.journal = Journal::default();
460 if self.state(range.clone(), &kind) == FormatState::On {
461 self.remove_marks(range, &kind);
462 } else {
463 for part in self.content_parts(range) {
464 self.add_mark(part, kind.clone());
465 }
466 }
467 }
468
469 /// An empty `url` removes the link.
470 pub fn set_link(&mut self, range: Range<usize>, url: &str) {
471 self.journal = Journal::default();
472 let link = MarkKind::Link(url.to_owned());
473 self.remove_marks(range.clone(), &link);
474 if !url.is_empty() {
475 for part in self.content_parts(range) {
476 self.add_mark(part, link.clone());
477 }
478 }
479 }
480
481 /// Returns the offset after the inserted link text.
482 pub fn insert_link(&mut self, offset: usize, text: &str, url: &str) -> usize {
483 self.journal = Journal::default();
484 self.splice(offset..offset, text, &[]);
485 self.add_mark(offset..offset + text.len(), MarkKind::Link(url.to_owned()));
486 offset + text.len()
487 }
488
489 /// Replaces `range`, the new text taking on the format of the text it replaces.
490 pub fn replace(&mut self, range: Range<usize>, text: &str) {
491 self.journal = Journal::default();
492 let kinds = self.style_for_insertion(range.start, range.end);
493 self.splice(range, text, &kinds);
494 }
495
496 /// Takes the composer text after an edit the user made. Returns the cursor, moved when a
497 /// marker had to be repaired or the typed text moved out of one.
498 pub fn apply_edit(
499 &mut self,
500 new_text: &str,
501 cursor: usize,
502 typing: Option<&TypingStyle>,
503 ) -> usize {
504 self.journal = Journal::default();
505 if new_text == self.text {
506 return cursor;
507 }
508 let (start, old_end, new_end) = edit_span(&self.text, new_text, cursor);
509 let replacement = new_text[start..new_end].to_owned();
510 let mut kinds = self.style_for_insertion(start, old_end);
511 if let Some(typing) = typing.filter(|typing| typing.at == start) {
512 kinds = typing.apply(kinds);
513 }
514 let marker = self.marker_range(self.line_at(start));
515 self.splice(start..old_end, &replacement, &kinds);
516 self.journal = Journal::default();
517 let mut cursor = cursor.min(self.text.len());
518 let typed_into_marker = old_end == start
519 && !replacement.contains('\n')
520 && !marker.is_empty()
521 && (marker.start..marker.end).contains(&start);
522 if typed_into_marker {
523 self.splice(start..start + replacement.len(), "", &[]);
524 self.splice(marker.end..marker.end, &replacement, &kinds);
525 cursor = marker.end + replacement.len();
526 }
527 self.repair(cursor)
528 }
529
530 /// Markdown typed just before `cursor` turns into formatting. Returns the new cursor and
531 /// the style for what is typed next, so text after `**bold**` is not bold.
532 pub fn convert_typed(&mut self, cursor: usize) -> Option<(usize, TypingStyle)> {
533 self.journal = Journal::default();
534 let index = self.line_at(cursor);
535 if matches!(self.lines[index], LineKind::Code(_)) {
536 return None;
537 }
538 let content = self.content_range(index);
539 if cursor < content.start || cursor > content.end {
540 return None;
541 }
542 let before = &self.text[content.start..cursor];
543 if self.lines[index] == LineKind::Text
544 && let Some((kind, number)) = line_shortcut(before)
545 {
546 self.splice(content.start..cursor, &marker_text(&kind, number), &[]);
547 self.lines[index] = kind;
548 let after_marker = self.content_range(index).start;
549 let cursor = self.repair(after_marker);
550 return Some((
551 cursor,
552 TypingStyle {
553 at: cursor,
554 ..TypingStyle::default()
555 },
556 ));
557 }
558 let (open, close, kind) = typed_inline(before)?;
559 let open = content.start + open.start..content.start + open.end;
560 let close = content.start + close.start..content.start + close.end;
561 let inside_code = self.marks.iter().any(|mark| {
562 mark.kind == MarkKind::Code
563 && (overlaps(&mark.range, &open) || overlaps(&mark.range, &close))
564 });
565 if inside_code {
566 return None;
567 }
568 self.splice(close.clone(), "", &[]);
569 self.splice(open.clone(), "", &[]);
570 let inner = open.start..close.start - open.len();
571 self.add_mark(inner, kind.clone());
572 let cursor = cursor - open.len() - close.len();
573 Some((
574 cursor,
575 TypingStyle {
576 at: cursor,
577 add: Vec::new(),
578 remove: vec![kind],
579 },
580 ))
581 }
582
583 /// Enter (or Shift+Enter) inside a list, quote or code block, or after a ``` fence.
584 /// `None` leaves the key to the caller: send, or a plain newline.
585 pub fn break_line(&mut self, cursor: usize, shift: bool) -> Option<usize> {
586 self.journal = Journal::default();
587 let index = self.line_at(cursor);
588 let kind = self.lines[index].clone();
589 let content = self.content_range(index);
590 let cursor = cursor.max(content.start);
591 match kind {
592 LineKind::Text => {
593 let language = fence_language(&self.text[content.clone()])?;
594 self.splice(content.clone(), "", &[]);
595 self.lines[index] = LineKind::Code(language);
596 Some(content.start)
597 }
598 LineKind::Quote if !shift => None,
599 LineKind::Quote => {
600 self.splice(cursor..cursor, "\n", &[]);
601 self.lines[index + 1] = LineKind::Quote;
602 self.splice(cursor + 1..cursor + 1, QUOTE_MARKER, &[]);
603 Some(cursor + 1 + QUOTE_MARKER.len())
604 }
605 LineKind::Code(_) => {
606 let last_of_block = self.lines.get(index + 1) != Some(&kind);
607 let block_continues_above = index > 0 && self.lines[index - 1] == kind;
608 if content.is_empty() && last_of_block && block_continues_above && !shift {
609 self.lines[index] = LineKind::Text;
610 return Some(cursor);
611 }
612 self.splice(cursor..cursor, "\n", &[]);
613 Some(cursor + 1)
614 }
615 list => {
616 if self.text[content.clone()].trim().is_empty() {
617 let lifted = match list.depth() {
618 0 => LineKind::Text,
619 depth => list.with_depth(depth - 1),
620 };
621 let cursor = self.set_line_kind(index, lifted, None, cursor);
622 return Some(self.repair(cursor));
623 }
624 self.splice(cursor..cursor, "\n", &[]);
625 self.lines[index + 1] = list;
626 let marker = self.expected_marker(index + 1, None);
627 self.splice(cursor + 1..cursor + 1, &marker, &[]);
628 Some(self.repair(cursor + 1 + marker.len()))
629 }
630 }
631 }
632
633 /// Backspace at the start of a formatted line drops (or lifts) its format.
634 pub fn backspace_at_start(&mut self, cursor: usize) -> Option<usize> {
635 self.journal = Journal::default();
636 let index = self.line_at(cursor);
637 let kind = self.lines[index].clone();
638 let line = self.line_ranges()[index].clone();
639 let content = self.content_range(index);
640 match &kind {
641 LineKind::Text => None,
642 LineKind::Code(_) => {
643 let first_of_block = index == 0 || self.lines[index - 1] != kind;
644 (cursor == content.start && first_of_block).then(|| {
645 self.lines[index] = LineKind::Text;
646 cursor
647 })
648 }
649 _ if cursor == line.start && index > 0 => {
650 self.splice(line.start - 1..content.start, "", &[]);
651 Some(self.repair(line.start - 1))
652 }
653 _ if cursor > line.start && cursor <= content.start => {
654 let lifted = match kind.depth() {
655 depth if kind.is_list() && depth > 0 => kind.with_depth(depth - 1),
656 _ => LineKind::Text,
657 };
658 let cursor = self.set_line_kind(index, lifted, None, cursor);
659 Some(self.repair(cursor))
660 }
661 _ => None,
662 }
663 }
664
665 /// Tab / Shift+Tab on list lines. `false` when a selected line is not a list item.
666 pub fn indent(&mut self, range: Range<usize>, outdent: bool) -> bool {
667 self.journal = Journal::default();
668 let lines = self.line_at(range.start)..=self.line_at(range.end);
669 if !lines.clone().all(|index| self.lines[index].is_list()) {
670 return false;
671 }
672 for index in lines {
673 let kind = self.lines[index].clone();
674 let depth = kind.depth();
675 let target = match (outdent, depth) {
676 (true, 0) => LineKind::Text,
677 (true, depth) => kind.with_depth(depth - 1),
678 (false, depth) => kind.with_depth((depth + 1).min(MAX_DEPTH)),
679 };
680 self.set_line_kind(index, target, None, 0);
681 }
682 self.repair(0);
683 true
684 }
685
686 /// All selected lines `kind` already: back to text. Otherwise all become `kind`.
687 pub fn toggle_lines(&mut self, range: Range<usize>, kind: LineKind) {
688 self.journal = Journal::default();
689 let lines = self.line_at(range.start)..=self.line_at(range.end);
690 let all = lines
691 .clone()
692 .all(|index| self.lines[index].same_format(&kind));
693 for index in lines {
694 let current = self.lines[index].clone();
695 let target = if all {
696 LineKind::Text
697 } else if current.same_format(&kind) {
698 current.clone()
699 } else if current.is_list() && kind.is_list() {
700 kind.with_depth(current.depth())
701 } else {
702 kind.clone()
703 };
704 if target != current {
705 self.set_line_kind(index, target, None, 0);
706 }
707 }
708 self.repair(0);
709 }
710
711 pub fn slice(&self, range: Range<usize>) -> Vec<DraftLine> {
712 let mut lines = Vec::new();
713 for (index, line) in self.line_ranges().into_iter().enumerate() {
714 if line.end < range.start || line.start > range.end {
715 continue;
716 }
717 let content = self.content_range(index);
718 let whole_start = range.start <= content.start;
719 let start = range.start.max(content.start);
720 let end = range.end.min(content.end).max(start);
721 let kind = if whole_start {
722 self.lines[index].clone()
723 } else {
724 LineKind::Text
725 };
726 let number = match kind {
727 LineKind::Numbered(depth) => {
728 numbered_marker(&self.text[line.clone()], depth).map(|(_, number)| number)
729 }
730 _ => None,
731 };
732 let marks = self
733 .marks
734 .iter()
735 .filter_map(|mark| {
736 let clipped = mark.range.start.max(start)..mark.range.end.min(end);
737 (!clipped.is_empty()).then(|| Mark {
738 range: clipped.start - start..clipped.end - start,
739 kind: mark.kind.clone(),
740 })
741 })
742 .collect();
743 lines.push(DraftLine {
744 kind,
745 number,
746 content: self.text[start..end].to_owned(),
747 marks,
748 });
749 }
750 lines
751 }
752
753 /// Puts `lines` in place of `range`. Returns the offset after the inserted content.
754 pub fn insert_lines(&mut self, range: Range<usize>, lines: &[DraftLine]) -> usize {
755 self.journal = Journal::default();
756 let index = self.line_at(range.start);
757 let content = self.content_range(index);
758 let start = range.start.max(content.start);
759 let range = start..range.end.max(start);
760 let tail_end = self.line_ranges()[self.line_at(range.end)].end;
761 let line_was_empty = self.lines[index] == LineKind::Text
762 && range.start == content.start
763 && range.end >= tail_end;
764 let joined = lines
765 .iter()
766 .map(|line| line.content.as_str())
767 .collect::<Vec<_>>()
768 .join("\n");
769 self.splice(range.clone(), &joined, &[]);
770 let mut offset = range.start;
771 for line in lines {
772 for mark in &line.marks {
773 self.add_mark(
774 offset + mark.range.start..offset + mark.range.end,
775 mark.kind.clone(),
776 );
777 }
778 offset += line.content.len() + 1;
779 }
780 for (position, line) in lines.iter().enumerate() {
781 let first_and_kept = position == 0 && !line_was_empty;
782 if first_and_kept || line.kind == self.lines[index + position] {
783 continue;
784 }
785 self.set_line_kind(index + position, line.kind.clone(), line.number, 0);
786 }
787 let last = index + lines.len().saturating_sub(1);
788 let end =
789 self.content_range(last).start + lines.last().map_or(0, |line| line.content.len());
790 self.repair(end)
791 }
792
793 /// Leading and trailing blank lines and spaces dropped.
794 pub fn trimmed(&self) -> Draft {
795 let mut lines = self.slice(0..self.text.len());
796 let blank =
797 |line: &DraftLine| line.kind == LineKind::Text && line.content.trim().is_empty();
798 while lines.len() > 1 && lines.first().is_some_and(blank) {
799 lines.remove(0);
800 }
801 while lines.len() > 1 && lines.last().is_some_and(blank) {
802 lines.pop();
803 }
804 if let Some(first) = lines.first_mut().filter(|line| line.kind == LineKind::Text) {
805 first.trim_start();
806 }
807 if let Some(last) = lines
808 .last_mut()
809 .filter(|line| !matches!(line.kind, LineKind::Code(_)))
810 {
811 last.trim_end();
812 }
813 Draft::from_lines(&lines)
814 }
815
816 /// Teams chat HTML.
817 pub fn to_html(&self) -> String {
818 let lines = self.slice(0..self.text.len());
819 let mut html = String::new();
820 let mut index = 0;
821 while index < lines.len() {
822 let kind = &lines[index].kind;
823 let run_end = index
824 + lines[index..]
825 .iter()
826 .take_while(|line| match kind {
827 LineKind::Code(_) => line.kind == *kind,
828 _ if kind.is_list() => line.kind.is_list(),
829 _ => line.kind.same_format(kind),
830 })
831 .count();
832 let run = &lines[index..run_end];
833 match kind {
834 LineKind::Text => html.push_str(&joined_inline(run)),
835 LineKind::Quote => {
836 html.push_str("<blockquote>");
837 html.push_str(&joined_inline(run));
838 html.push_str("</blockquote>");
839 }
840 LineKind::Code(language) => {
841 match language {
842 Some(language) => html.push_str(&format!(
843 "<pre class=\"language-{}\">",
844 escape_html(language)
845 )),
846 None => html.push_str("<pre>"),
847 }
848 let code = run
849 .iter()
850 .map(|line| escape_html(&line.content))
851 .collect::<Vec<_>>()
852 .join("\n");
853 html.push_str(&code);
854 html.push_str("</pre>");
855 }
856 _ => html.push_str(&list_html(run)),
857 }
858 index = run_end;
859 }
860 html
861 }
862
863 fn style_for_insertion(&self, start: usize, old_end: usize) -> Vec<MarkKind> {
864 let mut kinds: Vec<MarkKind> = self
865 .marks
866 .iter()
867 .filter(|mark| {
868 let range = &mark.range;
869 if old_end > start {
870 range.start <= start && start < range.end
871 } else {
872 (range.start < start && start < range.end)
873 || (range.start < start
874 && range.end == start
875 && mark.kind.continues_at_end())
876 }
877 })
878 .map(|mark| mark.kind.clone())
879 .collect();
880 kinds.sort();
881 kinds.dedup();
882 kinds
883 }
884
885 fn content_parts(&self, range: Range<usize>) -> Vec<Range<usize>> {
886 (self.line_at(range.start)..=self.line_at(range.end))
887 .map(|index| {
888 let content = self.content_range(index);
889 content.start.max(range.start)..content.end.min(range.end)
890 })
891 .filter(|part| !part.is_empty())
892 .collect()
893 }
894
895 fn add_mark(&mut self, range: Range<usize>, kind: MarkKind) {
896 if !range.is_empty() {
897 self.marks.push(Mark { range, kind });
898 self.normalize_marks();
899 }
900 }
901
902 fn remove_marks(&mut self, range: Range<usize>, kind: &MarkKind) {
903 let mut kept = Vec::with_capacity(self.marks.len());
904 for mark in std::mem::take(&mut self.marks) {
905 if !mark.kind.same_format(kind) || !overlaps(&mark.range, &range) {
906 kept.push(mark);
907 continue;
908 }
909 if mark.range.start < range.start {
910 kept.push(Mark {
911 range: mark.range.start..range.start,
912 kind: mark.kind.clone(),
913 });
914 }
915 if mark.range.end > range.end {
916 kept.push(Mark {
917 range: range.end..mark.range.end,
918 kind: mark.kind,
919 });
920 }
921 }
922 self.marks = kept;
923 self.normalize_marks();
924 }
925
926 fn normalize_marks(&mut self) {
927 let length = self.text.len();
928 let mut marks: Vec<Mark> = std::mem::take(&mut self.marks)
929 .into_iter()
930 .map(|mark| Mark {
931 range: mark.range.start.min(length)..mark.range.end.min(length),
932 kind: mark.kind,
933 })
934 .filter(|mark| !mark.range.is_empty())
935 .collect();
936 marks.sort_by(|left, right| {
937 left.kind
938 .cmp(&right.kind)
939 .then(left.range.start.cmp(&right.range.start))
940 });
941 let mut merged: Vec<Mark> = Vec::with_capacity(marks.len());
942 for mark in marks {
943 match merged.last_mut() {
944 Some(last) if last.kind == mark.kind && mark.range.start <= last.range.end => {
945 last.range.end = last.range.end.max(mark.range.end);
946 }
947 _ => merged.push(mark),
948 }
949 }
950 self.marks = merged;
951 }
952
953 fn splice(&mut self, range: Range<usize>, replacement: &str, kinds: &[MarkKind]) {
954 let (start, old_end) = (range.start, range.end);
955 let first_line = self.line_at(start);
956 let last_line = self.line_at(old_end);
957 let line_start = self.line_ranges()[first_line].start;
958 let breaks = replacement.matches('\n').count();
959 let kind = self.lines[first_line].clone();
960 let mut new_kinds = Vec::with_capacity(breaks + 1);
961 if breaks > 0 && start == line_start && old_end == start {
962 new_kinds.extend(std::iter::repeat_n(LineKind::Text, breaks));
963 new_kinds.push(kind);
964 } else {
965 let continued = match &kind {
966 LineKind::Code(language) => LineKind::Code(language.clone()),
967 _ => LineKind::Text,
968 };
969 new_kinds.push(kind);
970 new_kinds.extend(std::iter::repeat_n(continued, breaks));
971 }
972 self.lines.splice(first_line..=last_line, new_kinds);
973 self.text.replace_range(range.clone(), replacement);
974
975 let inserted = replacement.len();
976 let delta = inserted as isize - (old_end - start) as isize;
977 let shift = |position: usize| (position as isize + delta) as usize;
978 let map_start = |position: usize| {
979 if position < start {
980 position
981 } else if position >= old_end {
982 shift(position)
983 } else {
984 start + inserted
985 }
986 };
987 let map_end = |position: usize| {
988 if position <= start {
989 position
990 } else if position >= old_end {
991 shift(position)
992 } else {
993 start
994 }
995 };
996 for mark in &mut self.marks {
997 mark.range = map_start(mark.range.start)..map_end(mark.range.end);
998 }
999 if inserted > 0 {
1000 let inserted_range = start..start + inserted;
1001 let mut kept = Vec::with_capacity(self.marks.len() + kinds.len());
1002 for mark in std::mem::take(&mut self.marks) {
1003 if !overlaps(&mark.range, &inserted_range) || kinds.contains(&mark.kind) {
1004 kept.push(mark);
1005 continue;
1006 }
1007 if mark.range.start < inserted_range.start {
1008 kept.push(Mark {
1009 range: mark.range.start..inserted_range.start,
1010 kind: mark.kind.clone(),
1011 });
1012 }
1013 if mark.range.end > inserted_range.end {
1014 kept.push(Mark {
1015 range: inserted_range.end..mark.range.end,
1016 kind: mark.kind,
1017 });
1018 }
1019 }
1020 kept.extend(kinds.iter().map(|kind| Mark {
1021 range: inserted_range.clone(),
1022 kind: kind.clone(),
1023 }));
1024 self.marks = kept;
1025 }
1026 self.normalize_marks();
1027 self.journal.record(range, inserted, &self.text);
1028 }
1029
1030 fn previous_number(&self, index: usize, depth: u8) -> Option<u32> {
1031 let ranges = self.line_ranges();
1032 for previous in (0..index).rev() {
1033 match &self.lines[previous] {
1034 LineKind::Numbered(previous_depth) if *previous_depth == depth => {
1035 return numbered_marker(&self.text[ranges[previous].clone()], depth)
1036 .map(|(_, number)| number);
1037 }
1038 kind if kind.is_list() && kind.depth() > depth => continue,
1039 _ => return None,
1040 }
1041 }
1042 None
1043 }
1044
1045 fn expected_marker(&self, index: usize, own_number: Option<u32>) -> String {
1046 let kind = &self.lines[index];
1047 let number = match kind {
1048 LineKind::Numbered(depth) => match self.previous_number(index, *depth) {
1049 Some(previous) => previous + 1,
1050 None => own_number
1051 .or_else(|| {
1052 let line = self.line_ranges()[index].clone();
1053 numbered_marker(&self.text[line], *depth).map(|(_, number)| number)
1054 })
1055 .unwrap_or(1),
1056 },
1057 _ => 1,
1058 };
1059 marker_text(kind, number)
1060 }
1061
1062 fn set_line_kind(
1063 &mut self,
1064 index: usize,
1065 kind: LineKind,
1066 number: Option<u32>,
1067 cursor: usize,
1068 ) -> usize {
1069 let marker = self.marker_range(index);
1070 self.lines[index] = kind;
1071 let expected = self.expected_marker(index, number);
1072 self.replace_marker(marker, &expected, cursor)
1073 }
1074
1075 fn replace_marker(&mut self, marker: Range<usize>, expected: &str, cursor: usize) -> usize {
1076 if self.text[marker.clone()] == *expected {
1077 return cursor;
1078 }
1079 self.splice(marker.clone(), expected, &[]);
1080 if cursor >= marker.end {
1081 cursor + expected.len() - marker.len()
1082 } else if cursor > marker.start {
1083 marker.start + expected.len()
1084 } else {
1085 cursor
1086 }
1087 }
1088
1089 /// Lines whose marker was edited away become text; numbered items are renumbered.
1090 fn repair(&mut self, mut cursor: usize) -> usize {
1091 for index in 0..self.lines.len() {
1092 let kind = self.lines[index].clone();
1093 if matches!(kind, LineKind::Text | LineKind::Code(_)) {
1094 continue;
1095 }
1096 let line = self.line_ranges()[index].clone();
1097 let expected = self.expected_marker(index, None);
1098 let current = &self.text[line.clone()];
1099 if current.starts_with(&expected) {
1100 continue;
1101 }
1102 match numbered_marker(current, kind.depth()) {
1103 Some((length, _)) if matches!(kind, LineKind::Numbered(_)) => {
1104 cursor =
1105 self.replace_marker(line.start..line.start + length, &expected, cursor);
1106 }
1107 _ => self.lines[index] = LineKind::Text,
1108 }
1109 }
1110 cursor
1111 }
1112}
1113
1114fn overlaps(left: &Range<usize>, right: &Range<usize>) -> bool {
1115 left.start < right.end && right.start < left.end
1116}
1117
1118fn bullet_marker(depth: u8) -> String {
1119 format!(
1120 "{}{} ",
1121 INDENT.repeat(depth as usize),
1122 BULLETS[depth as usize % BULLETS.len()]
1123 )
1124}
1125
1126fn marker_text(kind: &LineKind, number: u32) -> String {
1127 match kind {
1128 LineKind::Bullet(depth) => bullet_marker(*depth),
1129 LineKind::Numbered(depth) => format!("{}{number}. ", INDENT.repeat(*depth as usize)),
1130 LineKind::Quote => QUOTE_MARKER.to_owned(),
1131 LineKind::Text | LineKind::Code(_) => String::new(),
1132 }
1133}
1134
1135fn marker_len(kind: &LineKind, line: &str) -> usize {
1136 match kind {
1137 LineKind::Bullet(depth) => {
1138 let marker = bullet_marker(*depth);
1139 if line.starts_with(&marker) {
1140 marker.len()
1141 } else {
1142 0
1143 }
1144 }
1145 LineKind::Numbered(depth) => numbered_marker(line, *depth).map_or(0, |(length, _)| length),
1146 LineKind::Quote if line.starts_with(QUOTE_MARKER) => QUOTE_MARKER.len(),
1147 _ => 0,
1148 }
1149}
1150
1151/// Byte length and number of a `1. ` marker at `depth`.
1152fn numbered_marker(line: &str, depth: u8) -> Option<(usize, u32)> {
1153 let indent = INDENT.repeat(depth as usize);
1154 let rest = line.strip_prefix(indent.as_str())?;
1155 let digits = rest.bytes().take_while(u8::is_ascii_digit).count();
1156 if digits == 0 || digits > 9 || !rest[digits..].starts_with(". ") {
1157 return None;
1158 }
1159 Some((indent.len() + digits + 2, rest[..digits].parse().ok()?))
1160}
1161
1162fn line_shortcut(before: &str) -> Option<(LineKind, u32)> {
1163 match before {
1164 "- " | "* " => Some((LineKind::Bullet(0), 1)),
1165 "> " => Some((LineKind::Quote, 1)),
1166 _ => {
1167 let digits = before.strip_suffix(". ")?;
1168 let all_digits = !digits.is_empty()
1169 && digits.len() <= 9
1170 && digits.bytes().all(|byte| byte.is_ascii_digit());
1171 all_digits.then(|| (LineKind::Numbered(0), digits.parse().unwrap_or(1)))
1172 }
1173 }
1174}
1175
1176fn fence_language(line: &str) -> Option<Option<String>> {
1177 let info = line.trim().strip_prefix(FENCE)?;
1178 let valid = info
1179 .chars()
1180 .all(|character| character.is_alphanumeric() || "+#-_.".contains(character));
1181 valid.then(|| (!info.is_empty()).then(|| info.to_lowercase()))
1182}
1183
1184fn valid_inner(inner: &str) -> bool {
1185 !inner.is_empty()
1186 && !inner.starts_with(char::is_whitespace)
1187 && !inner.ends_with(char::is_whitespace)
1188}
1189
1190fn word_before(text: &str) -> bool {
1191 text.chars()
1192 .next_back()
1193 .is_some_and(|character| character.is_alphanumeric())
1194}
1195
1196/// The markers of a format closed by the last typed character, relative to `before`.
1197fn typed_inline(before: &str) -> Option<(Range<usize>, Range<usize>, MarkKind)> {
1198 let end = before.len();
1199 if before.ends_with(')') {
1200 let captures = TYPED_LINK.captures(before)?;
1201 let whole = captures.get(0)?;
1202 let label = captures.get(1)?;
1203 return Some((
1204 whole.start()..whole.start() + 1,
1205 label.end()..end,
1206 MarkKind::Link(captures[2].to_owned()),
1207 ));
1208 }
1209 for (marker, kind) in [("**", MarkKind::Bold), ("~~", MarkKind::Strike)] {
1210 if let Some(body) = before.strip_suffix(marker) {
1211 let open = body.rfind(marker)?;
1212 return valid_inner(&body[open + 2..]).then(|| (open..open + 2, body.len()..end, kind));
1213 }
1214 }
1215 if let Some(body) = before.strip_suffix('`') {
1216 let open = body.rfind('`')?;
1217 let usable = !body[open + 1..].trim().is_empty() && !body[..open].ends_with('`');
1218 return usable.then(|| (open..open + 1, body.len()..end, MarkKind::Code));
1219 }
1220 for marker in ['*', '_'] {
1221 if let Some(body) = before.strip_suffix(marker) {
1222 if body.ends_with(marker) {
1223 return None;
1224 }
1225 let open = body.rfind(marker)?;
1226 let opening_ok = !word_before(&body[..open]) && !body[..open].ends_with(marker);
1227 return (opening_ok && valid_inner(&body[open + 1..]))
1228 .then(|| (open..open + 1, body.len()..end, MarkKind::Italic));
1229 }
1230 }
1231 None
1232}
1233
1234fn edit_span(old: &str, new: &str, cursor: usize) -> (usize, usize, usize) {
1235 let prefix = old
1236 .char_indices()
1237 .zip(new.chars())
1238 .find(|((_, left), right)| left != right)
1239 .map_or(old.len().min(new.len()), |((index, _), _)| index);
1240 let prefix = {
1241 let mut prefix = prefix.min(old.len()).min(new.len());
1242 while !old.is_char_boundary(prefix) || !new.is_char_boundary(prefix) {
1243 prefix -= 1;
1244 }
1245 prefix
1246 };
1247 let suffix = old[prefix..]
1248 .chars()
1249 .rev()
1250 .zip(new[prefix..].chars().rev())
1251 .take_while(|(left, right)| left == right)
1252 .map(|(character, _)| character.len_utf8())
1253 .sum::<usize>();
1254 let (start, old_end, new_end) = (prefix, old.len() - suffix, new.len() - suffix);
1255 let cursor = cursor.min(new.len());
1256 let pure = old_end == start || new_end == start;
1257 if pure && new_end > cursor && new_end - cursor <= start {
1258 let slide = new_end - cursor;
1259 let (slid_start, slid_old_end, slid_new_end) =
1260 (start - slide, old_end - slide, new_end - slide);
1261 let boundaries = [slid_start, slid_old_end]
1262 .iter()
1263 .all(|offset| old.is_char_boundary(*offset))
1264 && [slid_start, slid_new_end]
1265 .iter()
1266 .all(|offset| new.is_char_boundary(*offset));
1267 if boundaries && new[slid_new_end..] == old[slid_old_end..] {
1268 return (slid_start, slid_old_end, slid_new_end);
1269 }
1270 }
1271 (start, old_end, new_end)
1272}
1273
1274fn joined_inline(lines: &[DraftLine]) -> String {
1275 lines
1276 .iter()
1277 .map(|line| inline_html(&line.content, &line.marks))
1278 .collect::<Vec<_>>()
1279 .join("<br>")
1280}
1281
1282fn inline_html(content: &str, marks: &[Mark]) -> String {
1283 let mut boundaries: Vec<usize> = marks
1284 .iter()
1285 .flat_map(|mark| [mark.range.start, mark.range.end])
1286 .chain([0, content.len()])
1287 .filter(|offset| *offset <= content.len())
1288 .collect();
1289 boundaries.sort_unstable();
1290 boundaries.dedup();
1291 let mut html = String::new();
1292 let mut open: Vec<&MarkKind> = Vec::new();
1293 for window in boundaries.windows(2) {
1294 let segment = window[0]..window[1];
1295 let mut active: Vec<&MarkKind> = marks
1296 .iter()
1297 .filter(|mark| mark.range.start <= segment.start && segment.end <= mark.range.end)
1298 .map(|mark| &mark.kind)
1299 .collect();
1300 active.sort();
1301 active.dedup();
1302 let common = open
1303 .iter()
1304 .zip(active.iter())
1305 .take_while(|(left, right)| left == right)
1306 .count();
1307 for kind in open.drain(common..).rev() {
1308 html.push_str(kind.close_tag());
1309 }
1310 for kind in &active[common..] {
1311 html.push_str(&kind.open_tag());
1312 }
1313 open.extend(active[common..].iter().copied());
1314 html.push_str(&escape_html(&content[segment]));
1315 }
1316 for kind in open.into_iter().rev() {
1317 html.push_str(kind.close_tag());
1318 }
1319 html
1320}
1321
1322fn list_html(lines: &[DraftLine]) -> String {
1323 let close = |ordered: bool| if ordered { "</li></ol>" } else { "</li></ul>" };
1324 let mut html = String::new();
1325 let mut open: Vec<(u8, bool)> = Vec::new();
1326 for line in lines {
1327 let ordered = matches!(line.kind, LineKind::Numbered(_));
1328 let depth = line
1329 .kind
1330 .depth()
1331 .min(open.last().map_or(0, |(depth, _)| depth + 1));
1332 while open
1333 .last()
1334 .is_some_and(|(open_depth, _)| *open_depth > depth)
1335 {
1336 let (_, was_ordered) = open.pop().unwrap_or_default();
1337 html.push_str(close(was_ordered));
1338 }
1339 match open.last().copied() {
1340 Some((open_depth, open_ordered)) if open_depth == depth && open_ordered == ordered => {
1341 html.push_str("</li>");
1342 }
1343 Some((open_depth, open_ordered)) if open_depth == depth => {
1344 html.push_str(close(open_ordered));
1345 open.pop();
1346 html.push_str(&list_open(ordered, line.number));
1347 open.push((depth, ordered));
1348 }
1349 _ => {
1350 html.push_str(&list_open(ordered, line.number));
1351 open.push((depth, ordered));
1352 }
1353 }
1354 html.push_str("<li>");
1355 html.push_str(&inline_html(&line.content, &line.marks));
1356 }
1357 for (_, ordered) in open.into_iter().rev() {
1358 html.push_str(close(ordered));
1359 }
1360 html
1361}
1362
1363fn list_open(ordered: bool, number: Option<u32>) -> String {
1364 match (ordered, number) {
1365 (false, _) => "<ul>".to_owned(),
1366 (true, Some(start)) if start != 1 => format!("<ol start=\"{start}\">"),
1367 (true, _) => "<ol>".to_owned(),
1368 }
1369}
1370
1371/// Text that `from_markdown` would format: pasting it converts.
1372pub fn has_markdown(text: &str) -> bool {
1373 let draft = Draft::from_markdown(text);
1374 !draft.marks.is_empty() || draft.lines.iter().any(|kind| *kind != LineKind::Text)
1375}
1376
1377fn markdown_lines(text: &str) -> Vec<DraftLine> {
1378 let mut lines = Vec::new();
1379 let mut code: Option<Option<String>> = None;
1380 for raw in text.split('\n') {
1381 let raw = raw.strip_suffix('\r').unwrap_or(raw);
1382 let trimmed = raw.trim_start();
1383 if let Some(language) = &code {
1384 if trimmed.starts_with(FENCE) && trimmed.trim_end() == FENCE {
1385 code = None;
1386 } else {
1387 lines.push(DraftLine {
1388 kind: LineKind::Code(language.clone()),
1389 number: None,
1390 content: raw.to_owned(),
1391 marks: Vec::new(),
1392 });
1393 }
1394 continue;
1395 }
1396 if trimmed.starts_with(FENCE)
1397 && !trimmed[FENCE.len()..].contains('`')
1398 && let Some(language) = fence_language(trimmed)
1399 {
1400 code = Some(language);
1401 continue;
1402 }
1403 let indent: usize = raw[..raw.len() - trimmed.len()]
1404 .chars()
1405 .map(|character| if character == '\t' { 4 } else { 1 })
1406 .sum();
1407 let depth = ((indent / MARKDOWN_INDENT) as u8).min(MAX_DEPTH);
1408 let (kind, number, content) = if let Some(rest) = PASTED_BULLETS
1409 .iter()
1410 .find_map(|bullet| trimmed.strip_prefix(bullet))
1411 {
1412 (LineKind::Bullet(depth), None, rest)
1413 } else if let Some((length, number)) = numbered_marker(trimmed, 0) {
1414 (LineKind::Numbered(depth), Some(number), &trimmed[length..])
1415 } else if let Some(rest) = trimmed
1416 .strip_prefix("> ")
1417 .or_else(|| (trimmed == ">").then_some(""))
1418 {
1419 (LineKind::Quote, None, rest)
1420 } else {
1421 (LineKind::Text, None, raw)
1422 };
1423 let (content, marks) = parse_inline(content);
1424 lines.push(DraftLine {
1425 kind,
1426 number,
1427 content,
1428 marks,
1429 });
1430 }
1431 lines
1432}
1433
1434fn parse_inline(source: &str) -> (String, Vec<Mark>) {
1435 let mut text = String::with_capacity(source.len());
1436 let mut marks = Vec::new();
1437 parse_into(source, &mut text, &mut marks);
1438 (text, marks)
1439}
1440
1441fn parse_into(source: &str, text: &mut String, marks: &mut Vec<Mark>) {
1442 let mut rest = source;
1443 let mut previous: Option<char> = None;
1444 while let Some(character) = rest.chars().next() {
1445 if let Some((inner, consumed, kind)) = inline_at(rest, previous) {
1446 let start = text.len();
1447 if kind == MarkKind::Code {
1448 text.push_str(inner);
1449 } else {
1450 parse_into(inner, text, marks);
1451 }
1452 marks.push(Mark {
1453 range: start..text.len(),
1454 kind,
1455 });
1456 previous = rest[..consumed].chars().next_back();
1457 rest = &rest[consumed..];
1458 continue;
1459 }
1460 text.push(character);
1461 previous = Some(character);
1462 rest = &rest[character.len_utf8()..];
1463 }
1464}
1465
1466/// A format starting at the beginning of `rest`: its inner text, the bytes it spans, its kind.
1467fn inline_at(rest: &str, previous: Option<char>) -> Option<(&str, usize, MarkKind)> {
1468 if let Some(after) = rest.strip_prefix('`') {
1469 let end = after.find('`')?;
1470 let inner = &after[..end];
1471 return (!inner.trim().is_empty()).then_some((inner, end + 2, MarkKind::Code));
1472 }
1473 if rest.starts_with('[') {
1474 let captures = LINK_AT.captures(rest)?;
1475 let label = captures.get(1)?;
1476 return Some((
1477 label.as_str(),
1478 captures.get(0)?.end(),
1479 MarkKind::Link(captures[2].to_owned()),
1480 ));
1481 }
1482 for (marker, kind) in [("**", MarkKind::Bold), ("~~", MarkKind::Strike)] {
1483 if let Some(after) = rest.strip_prefix(marker) {
1484 let end = after.find(marker)?;
1485 let inner = &after[..end];
1486 return valid_inner(inner).then_some((inner, end + 4, kind));
1487 }
1488 }
1489 for marker in ['*', '_'] {
1490 let Some(after) = rest.strip_prefix(marker) else {
1491 continue;
1492 };
1493 if previous.is_some_and(char::is_alphanumeric) || after.starts_with(marker) {
1494 return None;
1495 }
1496 let end = after.find(marker)?;
1497 let inner = &after[..end];
1498 let followed_by_word = after[end + 1..]
1499 .chars()
1500 .next()
1501 .is_some_and(char::is_alphanumeric);
1502 return (valid_inner(inner) && !followed_by_word).then_some((
1503 inner,
1504 end + 2,
1505 MarkKind::Italic,
1506 ));
1507 }
1508 None
1509}
1510
1511#[derive(Default)]
1512struct SpanLines {
1513 lines: Vec<DraftLine>,
1514 open: bool,
1515}
1516
1517impl SpanLines {
1518 fn start_line(&mut self, kind: &LineKind, number: Option<u32>) {
1519 self.lines.push(DraftLine {
1520 kind: kind.clone(),
1521 number,
1522 content: String::new(),
1523 marks: Vec::new(),
1524 });
1525 self.open = true;
1526 }
1527
1528 fn append(&mut self, text: &str, kind: &LineKind, marks: &[MarkKind]) {
1529 for (index, piece) in text.split('\n').enumerate() {
1530 if index > 0 || !self.open {
1531 self.start_line(kind, None);
1532 }
1533 let Some(line) = self.lines.last_mut() else {
1534 continue;
1535 };
1536 let start = line.content.len();
1537 line.content.push_str(piece);
1538 let end = line.content.len();
1539 if end > start {
1540 line.marks.extend(marks.iter().map(|kind| Mark {
1541 range: start..end,
1542 kind: kind.clone(),
1543 }));
1544 }
1545 }
1546 }
1547
1548 fn walk(&mut self, spans: &[Span], kind: &LineKind, marks: &[MarkKind]) {
1549 let with = |extra: MarkKind| {
1550 let mut marks = marks.to_vec();
1551 marks.push(extra);
1552 marks
1553 };
1554 for (index, span) in spans.iter().enumerate() {
1555 let block_follows = matches!(
1556 spans.get(index + 1),
1557 Some(
1558 Span::List { .. }
1559 | Span::BlockQuote(_)
1560 | Span::CodeBlock { .. }
1561 | Span::Heading { .. }
1562 | Span::Table { .. }
1563 )
1564 );
1565 match span {
1566 Span::Text(text) => self.append(text, kind, marks),
1567 Span::Bold(children) => self.walk(children, kind, &with(MarkKind::Bold)),
1568 Span::Italic(children) => self.walk(children, kind, &with(MarkKind::Italic)),
1569 Span::Strike(children) => self.walk(children, kind, &with(MarkKind::Strike)),
1570 Span::Underline(children) => self.walk(children, kind, &with(MarkKind::Underline)),
1571 Span::Colored { children, .. } => self.walk(children, kind, marks),
1572 Span::Code(text) => self.append(text, kind, &with(MarkKind::Code)),
1573 Span::Link { url, children } => {
1574 self.walk(children, kind, &with(MarkKind::Link(url.clone())))
1575 }
1576 Span::Mention { name } => {
1577 self.append(&format!("@{}", name.trim_start_matches('@')), kind, marks)
1578 }
1579 Span::LineBreak | Span::Rule if !self.open || block_follows => {}
1580 Span::LineBreak | Span::Rule => {
1581 let continued = match kind {
1582 LineKind::Quote | LineKind::Code(_) => kind.clone(),
1583 _ => LineKind::Text,
1584 };
1585 self.start_line(&continued, None);
1586 }
1587 Span::Heading { children, .. } => {
1588 self.start_line(&LineKind::Text, None);
1589 self.walk(children, &LineKind::Text, &with(MarkKind::Bold));
1590 self.open = false;
1591 }
1592 Span::CodeBlock { language, code } => {
1593 let code_kind = LineKind::Code(language.clone());
1594 for line in code.trim_end_matches('\n').split('\n') {
1595 self.start_line(&code_kind, None);
1596 self.append(line, &code_kind, &[]);
1597 }
1598 self.open = false;
1599 }
1600 Span::BlockQuote(children) => {
1601 self.start_line(&LineKind::Quote, None);
1602 self.walk(children, &LineKind::Quote, marks);
1603 self.open = false;
1604 }
1605 Span::List {
1606 ordered,
1607 start,
1608 items,
1609 } => {
1610 let depth = if kind.is_list() {
1611 (kind.depth() + 1).min(MAX_DEPTH)
1612 } else {
1613 0
1614 };
1615 let item_kind = if *ordered {
1616 LineKind::Numbered(depth)
1617 } else {
1618 LineKind::Bullet(depth)
1619 };
1620 for (position, item) in items.iter().enumerate() {
1621 let number = (position == 0).then_some(*start);
1622 self.start_line(&item_kind, number);
1623 self.walk(item, &item_kind, marks);
1624 }
1625 self.open = false;
1626 }
1627 Span::Table { rows, .. } => {
1628 for row in rows {
1629 self.start_line(&LineKind::Text, None);
1630 for (position, cell) in row.iter().enumerate() {
1631 if position > 0 {
1632 self.append(" | ", &LineKind::Text, &[]);
1633 }
1634 self.walk(cell, &LineKind::Text, marks);
1635 }
1636 }
1637 self.open = false;
1638 }
1639 Span::Image { .. } | Span::Quote(_) => {}
1640 }
1641 }
1642 }
1643
1644 fn finish(mut self) -> Vec<DraftLine> {
1645 let blank =
1646 |line: &DraftLine| line.kind == LineKind::Text && line.content.trim().is_empty();
1647 while self.lines.len() > 1 && self.lines.last().is_some_and(blank) {
1648 self.lines.pop();
1649 }
1650 while self.lines.len() > 1 && self.lines.first().is_some_and(blank) {
1651 self.lines.remove(0);
1652 }
1653 if self.lines.is_empty() {
1654 self.lines.push(DraftLine::text(""));
1655 }
1656 self.lines
1657 }
1658}
1659
1660#[cfg(test)]
1661mod tests {
1662 use super::*;
1663 use crate::html_to_spans;
1664
1665 fn typed(draft: &mut Draft, text: &str) {
1666 let mut typing: Option<TypingStyle> = None;
1667 for character in text.chars() {
1668 let cursor = draft.text().len();
1669 let mut next = draft.text().to_owned();
1670 next.push(character);
1671 let cursor = draft.apply_edit(&next, cursor + character.len_utf8(), typing.as_ref());
1672 typing = draft.convert_typed(cursor).map(|(_, style)| style);
1673 draft.take_edits();
1674 }
1675 }
1676
1677 fn typed_draft(text: &str) -> Draft {
1678 let mut draft = Draft::default();
1679 typed(&mut draft, text);
1680 draft
1681 }
1682
1683 fn mark(range: Range<usize>, kind: MarkKind) -> Mark {
1684 Mark { range, kind }
1685 }
1686
1687 #[test]
1688 fn typed_markdown_becomes_formatting() {
1689 let draft = typed_draft("a **bold** and *it* or _it_ ~~gone~~ `code`");
1690 assert_eq!(draft.text(), "a bold and it or it gone code");
1691 assert_eq!(
1692 draft.marks(),
1693 [
1694 mark(2..6, MarkKind::Bold),
1695 mark(11..13, MarkKind::Italic),
1696 mark(17..19, MarkKind::Italic),
1697 mark(20..24, MarkKind::Strike),
1698 mark(25..29, MarkKind::Code),
1699 ]
1700 );
1701 }
1702
1703 #[test]
1704 fn typed_link_keeps_the_label_and_carries_the_url() {
1705 let draft = typed_draft("see [docs](https://example.com)");
1706 assert_eq!(draft.text(), "see docs");
1707 assert_eq!(
1708 draft.marks(),
1709 [mark(4..8, MarkKind::Link("https://example.com".into()))]
1710 );
1711 }
1712
1713 #[test]
1714 fn snake_case_and_spaced_stars_stay_text() {
1715 assert_eq!(typed_draft("snake_case_name").text(), "snake_case_name");
1716 assert_eq!(typed_draft("2 * 3 * 4").text(), "2 * 3 * 4");
1717 assert!(typed_draft("a** b**").marks().is_empty());
1718 }
1719
1720 #[test]
1721 fn typing_at_the_end_of_bold_continues_it_but_not_after_a_link() {
1722 let mut draft = Draft::plain("b");
1723 draft.toggle(0..1, MarkKind::Bold);
1724 typed(&mut draft, "x");
1725 assert_eq!(draft.marks(), [mark(0..2, MarkKind::Bold)]);
1726 let converted = typed_draft("**b**x");
1727 assert_eq!(converted.marks(), [mark(0..1, MarkKind::Bold)]);
1728 let mut linked = typed_draft("[a](u)");
1729 typed(&mut linked, "b");
1730 assert_eq!(linked.marks(), [mark(0..1, MarkKind::Link("u".into()))]);
1731 }
1732
1733 #[test]
1734 fn typing_style_switches_bold_on_and_off_for_the_next_text() {
1735 let mut draft = Draft::plain("ab");
1736 let typing = TypingStyle {
1737 at: 2,
1738 add: vec![MarkKind::Bold],
1739 remove: Vec::new(),
1740 };
1741 draft.apply_edit("abc", 3, Some(&typing));
1742 assert_eq!(draft.marks(), [mark(2..3, MarkKind::Bold)]);
1743 let off = TypingStyle {
1744 at: 3,
1745 add: Vec::new(),
1746 remove: vec![MarkKind::Bold],
1747 };
1748 draft.apply_edit("abcd", 4, Some(&off));
1749 assert_eq!(draft.marks(), [mark(2..3, MarkKind::Bold)]);
1750 }
1751
1752 #[test]
1753 fn toggle_on_a_mixed_selection_formats_all_then_clears() {
1754 let mut draft = Draft::plain("hello world");
1755 draft.toggle(0..5, MarkKind::Bold);
1756 assert_eq!(draft.state(0..11, &MarkKind::Bold), FormatState::Mixed);
1757 draft.toggle(0..11, MarkKind::Bold);
1758 assert_eq!(draft.state(0..11, &MarkKind::Bold), FormatState::On);
1759 draft.toggle(0..11, MarkKind::Bold);
1760 assert_eq!(draft.state(0..11, &MarkKind::Bold), FormatState::Off);
1761 assert!(draft.marks().is_empty());
1762 }
1763
1764 #[test]
1765 fn deleting_inside_and_across_marks_shifts_and_clips() {
1766 let mut draft = Draft::plain("aa bold cc");
1767 draft.toggle(3..7, MarkKind::Bold);
1768 draft.apply_edit("aa bld cc", 4, None);
1769 assert_eq!(draft.marks(), [mark(3..6, MarkKind::Bold)]);
1770 draft.apply_edit("ald cc", 1, None);
1771 assert_eq!(draft.marks(), [mark(1..3, MarkKind::Bold)]);
1772 draft.apply_edit("XXald cc", 2, None);
1773 assert_eq!(draft.marks(), [mark(3..5, MarkKind::Bold)]);
1774 }
1775
1776 #[test]
1777 fn repeated_characters_are_attributed_to_the_cursor() {
1778 let mut draft = Draft::plain("aa");
1779 draft.toggle(0..1, MarkKind::Bold);
1780 draft.apply_edit("aaa", 2, None);
1781 assert_eq!(draft.marks(), [mark(0..2, MarkKind::Bold)]);
1782 }
1783
1784 #[test]
1785 fn list_shortcuts_turn_lines_into_items() {
1786 let draft = typed_draft("- one");
1787 assert_eq!(draft.text(), "• one");
1788 assert_eq!(draft.lines(), [LineKind::Bullet(0)]);
1789 let numbered = typed_draft("1. one");
1790 assert_eq!(numbered.text(), "1. one");
1791 assert_eq!(numbered.lines(), [LineKind::Numbered(0)]);
1792 let quote = typed_draft("> said");
1793 assert_eq!(quote.text(), format!("{QUOTE_MARKER}said"));
1794 assert_eq!(quote.lines(), [LineKind::Quote]);
1795 }
1796
1797 #[test]
1798 fn enter_continues_a_list_and_ends_it_on_an_empty_item() {
1799 let mut draft = typed_draft("1. one");
1800 let cursor = draft.break_line(draft.text().len(), false).unwrap();
1801 assert_eq!(draft.text(), "1. one\n2. ");
1802 assert_eq!(cursor, draft.text().len());
1803 typed(&mut draft, "two");
1804 let cursor = draft.break_line(draft.text().len(), false).unwrap();
1805 let cursor = draft.break_line(cursor, false).unwrap();
1806 assert_eq!(draft.text(), "1. one\n2. two\n");
1807 assert_eq!(cursor, draft.text().len());
1808 assert_eq!(draft.lines()[2], LineKind::Text);
1809 assert_eq!(Draft::plain("x").break_line(1, false), None);
1810 }
1811
1812 #[test]
1813 fn enter_in_the_middle_of_an_item_splits_it_and_renumbers() {
1814 let mut draft = Draft::from_markdown("1. ab\n2. c");
1815 draft.break_line(4, false).unwrap();
1816 assert_eq!(draft.text(), "1. a\n2. b\n3. c");
1817 let edits = draft.take_edits();
1818 assert_eq!(map_offset(&edits, 4), 8);
1819 }
1820
1821 #[test]
1822 fn tab_nests_and_shift_tab_lifts_list_items() {
1823 let mut draft = Draft::from_markdown("- a\n- b");
1824 assert!(draft.indent(6..6, false));
1825 assert_eq!(draft.lines(), [LineKind::Bullet(0), LineKind::Bullet(1)]);
1826 assert_eq!(draft.text(), format!("• a\n{INDENT}◦ b"));
1827 assert!(draft.indent(draft.text().len()..draft.text().len(), true));
1828 assert!(draft.indent(draft.text().len()..draft.text().len(), true));
1829 assert_eq!(draft.text(), "• a\nb");
1830 assert!(!Draft::plain("x").indent(0..0, false));
1831 }
1832
1833 #[test]
1834 fn nested_numbering_counts_per_level() {
1835 let draft = Draft::from_markdown("1. a\n 1. x\n 2. y\n2. b");
1836 assert_eq!(
1837 draft.text(),
1838 format!("1. a\n{INDENT}1. x\n{INDENT}2. y\n2. b")
1839 );
1840 }
1841
1842 #[test]
1843 fn backspace_at_an_item_start_drops_the_bullet() {
1844 let mut draft = Draft::from_markdown("- a");
1845 let cursor = draft.backspace_at_start(bullet_marker(0).len()).unwrap();
1846 assert_eq!((draft.text(), cursor), ("a", 0));
1847 assert_eq!(draft.lines(), [LineKind::Text]);
1848 }
1849
1850 #[test]
1851 fn typing_before_a_bullet_lands_after_it() {
1852 let mut draft = Draft::from_markdown("- a");
1853 let marker = bullet_marker(0);
1854 let cursor = draft.apply_edit(&format!("x{marker}a"), 1, None);
1855 assert_eq!(draft.text(), format!("{marker}xa"));
1856 assert_eq!(cursor, marker.len() + 1);
1857 assert_eq!(
1858 draft.take_edits(),
1859 [
1860 (0..1, String::new()),
1861 (marker.len() + 1..marker.len() + 1, "x".to_owned())
1862 ]
1863 );
1864 }
1865
1866 #[test]
1867 fn a_damaged_marker_turns_the_line_into_text() {
1868 let mut draft = Draft::from_markdown("- a");
1869 draft.apply_edit("•a", 1, None);
1870 assert_eq!(draft.lines(), [LineKind::Text]);
1871 }
1872
1873 #[test]
1874 fn fence_and_enter_open_a_code_block_that_enter_continues() {
1875 let mut draft = typed_draft("```rust");
1876 let cursor = draft.break_line(draft.text().len(), false).unwrap();
1877 assert_eq!((draft.text(), cursor), ("", 0));
1878 assert_eq!(draft.lines(), [LineKind::Code(Some("rust".into()))]);
1879 typed(&mut draft, "fn x() {}");
1880 let cursor = draft.break_line(draft.text().len(), false).unwrap();
1881 assert_eq!(draft.lines().len(), 2);
1882 assert_eq!(draft.break_line(cursor, false), Some(cursor));
1883 assert_eq!(draft.lines()[1], LineKind::Text);
1884 assert_eq!(
1885 draft.to_html(),
1886 "<pre class=\"language-rust\">fn x() {}</pre>"
1887 );
1888 }
1889
1890 #[test]
1891 fn markdown_inside_code_stays_literal() {
1892 let mut draft = typed_draft("```");
1893 let cursor = draft.break_line(3, false).unwrap();
1894 assert_eq!(cursor, 0);
1895 typed(&mut draft, "a **b**");
1896 assert_eq!(draft.text(), "a **b**");
1897 assert!(draft.marks().is_empty());
1898 }
1899
1900 #[test]
1901 fn html_nests_overlapping_marks_and_escapes() {
1902 let mut draft = Draft::plain("a<b & c");
1903 draft.toggle(0..4, MarkKind::Bold);
1904 draft.toggle(2..7, MarkKind::Italic);
1905 assert_eq!(draft.to_html(), "<b>a&lt;<i>b </i></b><i>&amp; c</i>");
1906 }
1907
1908 #[test]
1909 fn html_covers_every_format() {
1910 let draft = Draft::from_markdown(
1911 "**b** *i* ~~s~~ `c` [l](https://x.test/?a=1&b=2)\n> q1\n> q2\n- a\n - b\n1. x\n2. y\n```py\nprint(1)\n```",
1912 );
1913 let mut underlined = draft.clone();
1914 underlined.toggle(0..1, MarkKind::Underline);
1915 assert_eq!(
1916 underlined.to_html(),
1917 "<b><u>b</u></b> <i>i</i> <s>s</s> <code>c</code> <a href=\"https://x.test/?a=1&amp;b=2\">l</a>\
1918 <blockquote>q1<br>q2</blockquote>\
1919 <ul><li>a<ul><li>b</li></ul></li></ul>\
1920 <ol><li>x</li><li>y</li></ol>\
1921 <pre class=\"language-py\">print(1)</pre>"
1922 );
1923 }
1924
1925 #[test]
1926 fn ordered_lists_keep_their_start() {
1927 let draft = Draft::from_markdown("3. c\n4. d");
1928 assert_eq!(draft.to_html(), "<ol start=\"3\"><li>c</li><li>d</li></ol>");
1929 }
1930
1931 #[test]
1932 fn spans_round_trip_through_html() {
1933 let source = Draft::from_markdown(
1934 "hi **bold _both_** `c` [l](https://x.test)\n> quoted\n- a\n - b\n2. two\n3. three\n```rs\nlet x = 1;\n```\nend",
1935 );
1936 let back = Draft::from_spans(&html_to_spans(&source.to_html()));
1937 assert_eq!(back.text(), source.text());
1938 assert_eq!(back.lines(), source.lines());
1939 assert_eq!(back.marks(), source.marks());
1940 }
1941
1942 #[test]
1943 fn mentions_from_html_come_back_as_at_text() {
1944 let draft = Draft::from_spans(&html_to_spans("hi <at id=\"0\">Ada</at> <b>now</b>"));
1945 assert_eq!(draft.text(), "hi @Ada now");
1946 assert_eq!(draft.marks(), [mark(8..11, MarkKind::Bold)]);
1947 }
1948
1949 #[test]
1950 fn pasted_markdown_is_detected() {
1951 assert!(has_markdown("see **this**"));
1952 assert!(has_markdown("- a\n- b"));
1953 assert!(has_markdown("```\nx\n```"));
1954 assert!(!has_markdown("plain text, 2*3=6 and snake_case"));
1955 }
1956
1957 #[test]
1958 fn slices_carry_formatting_into_another_draft() {
1959 let source = Draft::from_markdown("intro **bold**\n- one\n- two");
1960 let end = source.text().len();
1961 let fragment = source.slice(6..end);
1962 assert_eq!(fragment[0].kind, LineKind::Text);
1963 assert_eq!(fragment[1].kind, LineKind::Bullet(0));
1964 let mut target = Draft::plain("x ");
1965 let cursor = target.insert_lines(2..2, &fragment);
1966 assert_eq!(target.text(), "x bold\n• one\n• two");
1967 assert_eq!(cursor, target.text().len());
1968 assert_eq!(target.marks(), [mark(2..6, MarkKind::Bold)]);
1969 assert_eq!(
1970 target.lines()[1..],
1971 [LineKind::Bullet(0), LineKind::Bullet(0)]
1972 );
1973 }
1974
1975 #[test]
1976 fn markdown_pasted_on_its_own_line_converts_from_the_first_line() {
1977 let raw = "- a\n- b";
1978 let mut draft = Draft::plain("");
1979 draft.apply_edit(raw, raw.len(), None);
1980 let lines = Draft::from_markdown(raw).slice(0..usize::MAX);
1981 let cursor = draft.insert_lines(0..raw.len(), &lines);
1982 assert_eq!(draft.text(), "• a\n• b");
1983 assert_eq!(cursor, draft.text().len());
1984 let mut inline = Draft::plain("x ");
1985 inline.apply_edit("x **b**", 7, None);
1986 let lines = Draft::from_markdown("**b**").slice(0..usize::MAX);
1987 inline.insert_lines(2..7, &lines);
1988 assert_eq!(inline.text(), "x b");
1989 assert_eq!(inline.marks(), [mark(2..3, MarkKind::Bold)]);
1990 }
1991
1992 #[test]
1993 fn journal_merges_edits_into_ranges_of_the_old_text() {
1994 let mut draft = Draft::plain("a **b** c");
1995 draft.splice(5..7, "", &[]);
1996 draft.splice(2..4, "", &[]);
1997 draft.splice(0..0, "X", &[]);
1998 let edits = draft.take_edits();
1999 assert_eq!(
2000 edits,
2001 [
2002 (0..0, "X".to_owned()),
2003 (2..4, String::new()),
2004 (5..7, String::new())
2005 ]
2006 );
2007 assert_eq!(
2008 reverse_edits(&edits, "a **b** c")[1],
2009 (3..3, "**".to_owned())
2010 );
2011 let mut touching = Draft::plain("abc");
2012 touching.splice(1..2, "XY", &[]);
2013 touching.splice(3..3, "Z", &[]);
2014 assert_eq!(touching.take_edits(), [(1..2, "XYZ".to_owned())]);
2015 }
2016
2017 #[test]
2018 fn trimming_drops_blank_lines_and_outer_spaces() {
2019 let mut draft = Draft::plain("\n hi **x** \n\n");
2020 draft.toggle(6..11, MarkKind::Bold);
2021 let trimmed = draft.trimmed();
2022 assert_eq!(trimmed.text(), "hi **x**");
2023 assert_eq!(trimmed.marks(), [mark(3..8, MarkKind::Bold)]);
2024 }
2025
2026 #[test]
2027 fn toolbar_line_toggles_apply_to_every_selected_line() {
2028 let mut draft = Draft::plain("a\nb");
2029 draft.toggle_lines(0..3, LineKind::Numbered(0));
2030 assert_eq!(draft.text(), "1. a\n2. b");
2031 assert_eq!(
2032 draft.line_state(0..4, &LineKind::Numbered(0)),
2033 FormatState::On
2034 );
2035 draft.toggle_lines(0..9, LineKind::Bullet(0));
2036 assert_eq!(draft.text(), "• a\n• b");
2037 let end = draft.text().len();
2038 draft.toggle_lines(0..end, LineKind::Bullet(0));
2039 assert_eq!(draft.text(), "a\nb");
2040 }
2041
2042 #[test]
2043 fn links_are_set_replaced_and_removed() {
2044 let mut draft = Draft::plain("go here");
2045 draft.set_link(3..7, "https://a.test");
2046 assert_eq!(draft.link_in(4..4), Some("https://a.test".into()));
2047 draft.set_link(3..7, "");
2048 assert!(draft.marks().is_empty());
2049 let end = draft.insert_link(7, " https://b.test", "https://b.test");
2050 assert_eq!(end, draft.text().len());
2051 }
2052}