BlueGit

ict rusty-teams

feat(core): rich draft model and Teams HTML

- Draft: text with list and quote markers, marks (bold, italic,
  underline, strike, code, link) and a kind per line
- Edits diff old and new text, shift and clip marks, continue bold,
  italic, underline and strike typed at their end
- Markdown typed or pasted converts; Enter, Tab and Backspace rules for
  lists, quotes and code blocks; numbered items renumber
- to_html for Teams (nested ul/ol with start, blockquote, pre with
  language class) and from_spans for editing a sent message
- Edit journal so the composer applies changes without touching
  mention tokens

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-08 · 7 weeks ago

Hash
ae1cb2ad924827f6f1e8baca75b7351fdf4ffef3
Parent
0c8e684d
3 files changed +2047 −0
crates/core/src/draft.rs added +2032 −0
@@ -0,0 +1,2032 @@
1 use std::ops::Range;
2 use std::sync::LazyLock;
3
4 use regex::Regex;
5 use serde::{Deserialize, Serialize};
6
7 use crate::markdown::escape_html;
8 use crate::spans::Span;
9
10 pub const MAX_DEPTH: u8 = 2;
11 const BULLETS: [&str; 3] = ["•", "◦", "▪"];
12 const PASTED_BULLETS: [&str; 6] = ["- ", "* ", "+ ", "• ", "◦ ", "▪ "];
13 const INDENT: &str = "\u{2003}\u{2003}";
14 const QUOTE_MARKER: &str = "\u{2003}";
15 const FENCE: &str = "```";
16 const MARKDOWN_INDENT: usize = 2;
17
18 static TYPED_LINK: LazyLock<Regex> =
19 LazyLock::new(|| Regex::new(r"\[([^\]\n]+)\]\(([^)\s]+)\)$").unwrap());
20 static 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)]
24 pub enum MarkKind {
25 Link(String),
26 Bold,
27 Italic,
28 Underline,
29 Strike,
30 Code,
31 }
32
33 impl 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)]
69 pub struct Mark {
70 pub range: Range<usize>,
71 pub kind: MarkKind,
72 }
73
74 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
75 pub enum LineKind {
76 Text,
77 Bullet(u8),
78 Numbered(u8),
79 Quote,
80 Code(Option<String>),
81 }
82
83 impl 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)]
109 pub 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)]
117 pub struct TypingStyle {
118 pub at: usize,
119 pub add: Vec<MarkKind>,
120 pub remove: Vec<MarkKind>,
121 }
122
123 impl 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)]
156 pub struct DraftLine {
157 pub kind: LineKind,
158 pub number: Option<u32>,
159 pub content: String,
160 pub marks: Vec<Mark>,
161 }
162
163 impl 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
192 pub 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)]
196 struct Journal(Vec<Edit>);
197
198 impl PartialEq for Journal {
199 fn eq(&self, _: &Journal) -> bool {
200 true
201 }
202 }
203
204 impl Eq for Journal {}
205
206 impl 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.
260 pub 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`.
275 pub 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)]
292 pub struct Draft {
293 text: String,
294 marks: Vec<Mark>,
295 lines: Vec<LineKind>,
296 journal: Journal,
297 }
298
299 impl Default for Draft {
300 fn default() -> Self {
301 Draft::plain("")
302 }
303 }
304
305 impl 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 line_was_empty = self.lines[index] == LineKind::Text && content.is_empty();
761 let joined = lines
762 .iter()
763 .map(|line| line.content.as_str())
764 .collect::<Vec<_>>()
765 .join("\n");
766 self.splice(range.clone(), &joined, &[]);
767 let mut offset = range.start;
768 for line in lines {
769 for mark in &line.marks {
770 self.add_mark(
771 offset + mark.range.start..offset + mark.range.end,
772 mark.kind.clone(),
773 );
774 }
775 offset += line.content.len() + 1;
776 }
777 for (position, line) in lines.iter().enumerate() {
778 let first_and_kept = position == 0 && !line_was_empty;
779 if first_and_kept || line.kind == self.lines[index + position] {
780 continue;
781 }
782 self.set_line_kind(index + position, line.kind.clone(), line.number, 0);
783 }
784 let last = index + lines.len().saturating_sub(1);
785 let end =
786 self.content_range(last).start + lines.last().map_or(0, |line| line.content.len());
787 self.repair(end)
788 }
789
790 /// Leading and trailing blank lines and spaces dropped.
791 pub fn trimmed(&self) -> Draft {
792 let mut lines = self.slice(0..self.text.len());
793 let blank =
794 |line: &DraftLine| line.kind == LineKind::Text && line.content.trim().is_empty();
795 while lines.len() > 1 && lines.first().is_some_and(blank) {
796 lines.remove(0);
797 }
798 while lines.len() > 1 && lines.last().is_some_and(blank) {
799 lines.pop();
800 }
801 if let Some(first) = lines.first_mut().filter(|line| line.kind == LineKind::Text) {
802 first.trim_start();
803 }
804 if let Some(last) = lines
805 .last_mut()
806 .filter(|line| !matches!(line.kind, LineKind::Code(_)))
807 {
808 last.trim_end();
809 }
810 Draft::from_lines(&lines)
811 }
812
813 /// Teams chat HTML.
814 pub fn to_html(&self) -> String {
815 let lines = self.slice(0..self.text.len());
816 let mut html = String::new();
817 let mut index = 0;
818 while index < lines.len() {
819 let kind = &lines[index].kind;
820 let run_end = index
821 + lines[index..]
822 .iter()
823 .take_while(|line| match kind {
824 LineKind::Code(_) => line.kind == *kind,
825 _ if kind.is_list() => line.kind.is_list(),
826 _ => line.kind.same_format(kind),
827 })
828 .count();
829 let run = &lines[index..run_end];
830 match kind {
831 LineKind::Text => html.push_str(&joined_inline(run)),
832 LineKind::Quote => {
833 html.push_str("<blockquote>");
834 html.push_str(&joined_inline(run));
835 html.push_str("</blockquote>");
836 }
837 LineKind::Code(language) => {
838 match language {
839 Some(language) => html.push_str(&format!(
840 "<pre class=\"language-{}\">",
841 escape_html(language)
842 )),
843 None => html.push_str("<pre>"),
844 }
845 let code = run
846 .iter()
847 .map(|line| escape_html(&line.content))
848 .collect::<Vec<_>>()
849 .join("\n");
850 html.push_str(&code);
851 html.push_str("</pre>");
852 }
853 _ => html.push_str(&list_html(run)),
854 }
855 index = run_end;
856 }
857 html
858 }
859
860 fn style_for_insertion(&self, start: usize, old_end: usize) -> Vec<MarkKind> {
861 let mut kinds: Vec<MarkKind> = self
862 .marks
863 .iter()
864 .filter(|mark| {
865 let range = &mark.range;
866 if old_end > start {
867 range.start <= start && start < range.end
868 } else {
869 (range.start < start && start < range.end)
870 || (range.start < start
871 && range.end == start
872 && mark.kind.continues_at_end())
873 }
874 })
875 .map(|mark| mark.kind.clone())
876 .collect();
877 kinds.sort();
878 kinds.dedup();
879 kinds
880 }
881
882 fn content_parts(&self, range: Range<usize>) -> Vec<Range<usize>> {
883 (self.line_at(range.start)..=self.line_at(range.end))
884 .map(|index| {
885 let content = self.content_range(index);
886 content.start.max(range.start)..content.end.min(range.end)
887 })
888 .filter(|part| !part.is_empty())
889 .collect()
890 }
891
892 fn add_mark(&mut self, range: Range<usize>, kind: MarkKind) {
893 if !range.is_empty() {
894 self.marks.push(Mark { range, kind });
895 self.normalize_marks();
896 }
897 }
898
899 fn remove_marks(&mut self, range: Range<usize>, kind: &MarkKind) {
900 let mut kept = Vec::with_capacity(self.marks.len());
901 for mark in std::mem::take(&mut self.marks) {
902 if !mark.kind.same_format(kind) || !overlaps(&mark.range, &range) {
903 kept.push(mark);
904 continue;
905 }
906 if mark.range.start < range.start {
907 kept.push(Mark {
908 range: mark.range.start..range.start,
909 kind: mark.kind.clone(),
910 });
911 }
912 if mark.range.end > range.end {
913 kept.push(Mark {
914 range: range.end..mark.range.end,
915 kind: mark.kind,
916 });
917 }
918 }
919 self.marks = kept;
920 self.normalize_marks();
921 }
922
923 fn normalize_marks(&mut self) {
924 let length = self.text.len();
925 let mut marks: Vec<Mark> = std::mem::take(&mut self.marks)
926 .into_iter()
927 .map(|mark| Mark {
928 range: mark.range.start.min(length)..mark.range.end.min(length),
929 kind: mark.kind,
930 })
931 .filter(|mark| !mark.range.is_empty())
932 .collect();
933 marks.sort_by(|left, right| {
934 left.kind
935 .cmp(&right.kind)
936 .then(left.range.start.cmp(&right.range.start))
937 });
938 let mut merged: Vec<Mark> = Vec::with_capacity(marks.len());
939 for mark in marks {
940 match merged.last_mut() {
941 Some(last) if last.kind == mark.kind && mark.range.start <= last.range.end => {
942 last.range.end = last.range.end.max(mark.range.end);
943 }
944 _ => merged.push(mark),
945 }
946 }
947 self.marks = merged;
948 }
949
950 fn splice(&mut self, range: Range<usize>, replacement: &str, kinds: &[MarkKind]) {
951 let (start, old_end) = (range.start, range.end);
952 let first_line = self.line_at(start);
953 let last_line = self.line_at(old_end);
954 let line_start = self.line_ranges()[first_line].start;
955 let breaks = replacement.matches('\n').count();
956 let kind = self.lines[first_line].clone();
957 let mut new_kinds = Vec::with_capacity(breaks + 1);
958 if breaks > 0 && start == line_start && old_end == start {
959 new_kinds.extend(std::iter::repeat_n(LineKind::Text, breaks));
960 new_kinds.push(kind);
961 } else {
962 let continued = match &kind {
963 LineKind::Code(language) => LineKind::Code(language.clone()),
964 _ => LineKind::Text,
965 };
966 new_kinds.push(kind);
967 new_kinds.extend(std::iter::repeat_n(continued, breaks));
968 }
969 self.lines.splice(first_line..=last_line, new_kinds);
970 self.text.replace_range(range.clone(), replacement);
971
972 let inserted = replacement.len();
973 let delta = inserted as isize - (old_end - start) as isize;
974 let shift = |position: usize| (position as isize + delta) as usize;
975 let map_start = |position: usize| {
976 if position < start {
977 position
978 } else if position >= old_end {
979 shift(position)
980 } else {
981 start + inserted
982 }
983 };
984 let map_end = |position: usize| {
985 if position <= start {
986 position
987 } else if position >= old_end {
988 shift(position)
989 } else {
990 start
991 }
992 };
993 for mark in &mut self.marks {
994 mark.range = map_start(mark.range.start)..map_end(mark.range.end);
995 }
996 if inserted > 0 {
997 let inserted_range = start..start + inserted;
998 let mut kept = Vec::with_capacity(self.marks.len() + kinds.len());
999 for mark in std::mem::take(&mut self.marks) {
1000 if !overlaps(&mark.range, &inserted_range) || kinds.contains(&mark.kind) {
1001 kept.push(mark);
1002 continue;
1003 }
1004 if mark.range.start < inserted_range.start {
1005 kept.push(Mark {
1006 range: mark.range.start..inserted_range.start,
1007 kind: mark.kind.clone(),
1008 });
1009 }
1010 if mark.range.end > inserted_range.end {
1011 kept.push(Mark {
1012 range: inserted_range.end..mark.range.end,
1013 kind: mark.kind,
1014 });
1015 }
1016 }
1017 kept.extend(kinds.iter().map(|kind| Mark {
1018 range: inserted_range.clone(),
1019 kind: kind.clone(),
1020 }));
1021 self.marks = kept;
1022 }
1023 self.normalize_marks();
1024 self.journal.record(range, inserted, &self.text);
1025 }
1026
1027 fn previous_number(&self, index: usize, depth: u8) -> Option<u32> {
1028 let ranges = self.line_ranges();
1029 for previous in (0..index).rev() {
1030 match &self.lines[previous] {
1031 LineKind::Numbered(previous_depth) if *previous_depth == depth => {
1032 return numbered_marker(&self.text[ranges[previous].clone()], depth)
1033 .map(|(_, number)| number);
1034 }
1035 kind if kind.is_list() && kind.depth() > depth => continue,
1036 _ => return None,
1037 }
1038 }
1039 None
1040 }
1041
1042 fn expected_marker(&self, index: usize, own_number: Option<u32>) -> String {
1043 let kind = &self.lines[index];
1044 let number = match kind {
1045 LineKind::Numbered(depth) => match self.previous_number(index, *depth) {
1046 Some(previous) => previous + 1,
1047 None => own_number
1048 .or_else(|| {
1049 let line = self.line_ranges()[index].clone();
1050 numbered_marker(&self.text[line], *depth).map(|(_, number)| number)
1051 })
1052 .unwrap_or(1),
1053 },
1054 _ => 1,
1055 };
1056 marker_text(kind, number)
1057 }
1058
1059 fn set_line_kind(
1060 &mut self,
1061 index: usize,
1062 kind: LineKind,
1063 number: Option<u32>,
1064 cursor: usize,
1065 ) -> usize {
1066 let marker = self.marker_range(index);
1067 self.lines[index] = kind;
1068 let expected = self.expected_marker(index, number);
1069 self.replace_marker(marker, &expected, cursor)
1070 }
1071
1072 fn replace_marker(&mut self, marker: Range<usize>, expected: &str, cursor: usize) -> usize {
1073 if self.text[marker.clone()] == *expected {
1074 return cursor;
1075 }
1076 self.splice(marker.clone(), expected, &[]);
1077 if cursor >= marker.end {
1078 cursor + expected.len() - marker.len()
1079 } else if cursor > marker.start {
1080 marker.start + expected.len()
1081 } else {
1082 cursor
1083 }
1084 }
1085
1086 /// Lines whose marker was edited away become text; numbered items are renumbered.
1087 fn repair(&mut self, mut cursor: usize) -> usize {
1088 for index in 0..self.lines.len() {
1089 let kind = self.lines[index].clone();
1090 if matches!(kind, LineKind::Text | LineKind::Code(_)) {
1091 continue;
1092 }
1093 let line = self.line_ranges()[index].clone();
1094 let expected = self.expected_marker(index, None);
1095 let current = &self.text[line.clone()];
1096 if current.starts_with(&expected) {
1097 continue;
1098 }
1099 match numbered_marker(current, kind.depth()) {
1100 Some((length, _)) if matches!(kind, LineKind::Numbered(_)) => {
1101 cursor =
1102 self.replace_marker(line.start..line.start + length, &expected, cursor);
1103 }
1104 _ => self.lines[index] = LineKind::Text,
1105 }
1106 }
1107 cursor
1108 }
1109 }
1110
1111 fn overlaps(left: &Range<usize>, right: &Range<usize>) -> bool {
1112 left.start < right.end && right.start < left.end
1113 }
1114
1115 fn bullet_marker(depth: u8) -> String {
1116 format!(
1117 "{}{} ",
1118 INDENT.repeat(depth as usize),
1119 BULLETS[depth as usize % BULLETS.len()]
1120 )
1121 }
1122
1123 fn marker_text(kind: &LineKind, number: u32) -> String {
1124 match kind {
1125 LineKind::Bullet(depth) => bullet_marker(*depth),
1126 LineKind::Numbered(depth) => format!("{}{number}. ", INDENT.repeat(*depth as usize)),
1127 LineKind::Quote => QUOTE_MARKER.to_owned(),
1128 LineKind::Text | LineKind::Code(_) => String::new(),
1129 }
1130 }
1131
1132 fn marker_len(kind: &LineKind, line: &str) -> usize {
1133 match kind {
1134 LineKind::Bullet(depth) => {
1135 let marker = bullet_marker(*depth);
1136 if line.starts_with(&marker) {
1137 marker.len()
1138 } else {
1139 0
1140 }
1141 }
1142 LineKind::Numbered(depth) => numbered_marker(line, *depth).map_or(0, |(length, _)| length),
1143 LineKind::Quote if line.starts_with(QUOTE_MARKER) => QUOTE_MARKER.len(),
1144 _ => 0,
1145 }
1146 }
1147
1148 /// Byte length and number of a `1. ` marker at `depth`.
1149 fn numbered_marker(line: &str, depth: u8) -> Option<(usize, u32)> {
1150 let indent = INDENT.repeat(depth as usize);
1151 let rest = line.strip_prefix(indent.as_str())?;
1152 let digits = rest.bytes().take_while(u8::is_ascii_digit).count();
1153 if digits == 0 || digits > 9 || !rest[digits..].starts_with(". ") {
1154 return None;
1155 }
1156 Some((indent.len() + digits + 2, rest[..digits].parse().ok()?))
1157 }
1158
1159 fn line_shortcut(before: &str) -> Option<(LineKind, u32)> {
1160 match before {
1161 "- " | "* " => Some((LineKind::Bullet(0), 1)),
1162 "> " => Some((LineKind::Quote, 1)),
1163 _ => {
1164 let digits = before.strip_suffix(". ")?;
1165 let all_digits = !digits.is_empty()
1166 && digits.len() <= 9
1167 && digits.bytes().all(|byte| byte.is_ascii_digit());
1168 all_digits.then(|| (LineKind::Numbered(0), digits.parse().unwrap_or(1)))
1169 }
1170 }
1171 }
1172
1173 fn fence_language(line: &str) -> Option<Option<String>> {
1174 let info = line.trim().strip_prefix(FENCE)?;
1175 let valid = info
1176 .chars()
1177 .all(|character| character.is_alphanumeric() || "+#-_.".contains(character));
1178 valid.then(|| (!info.is_empty()).then(|| info.to_lowercase()))
1179 }
1180
1181 fn valid_inner(inner: &str) -> bool {
1182 !inner.is_empty()
1183 && !inner.starts_with(char::is_whitespace)
1184 && !inner.ends_with(char::is_whitespace)
1185 }
1186
1187 fn word_before(text: &str) -> bool {
1188 text.chars()
1189 .next_back()
1190 .is_some_and(|character| character.is_alphanumeric())
1191 }
1192
1193 /// The markers of a format closed by the last typed character, relative to `before`.
1194 fn typed_inline(before: &str) -> Option<(Range<usize>, Range<usize>, MarkKind)> {
1195 let end = before.len();
1196 if before.ends_with(')') {
1197 let captures = TYPED_LINK.captures(before)?;
1198 let whole = captures.get(0)?;
1199 let label = captures.get(1)?;
1200 return Some((
1201 whole.start()..whole.start() + 1,
1202 label.end()..end,
1203 MarkKind::Link(captures[2].to_owned()),
1204 ));
1205 }
1206 for (marker, kind) in [("**", MarkKind::Bold), ("~~", MarkKind::Strike)] {
1207 if let Some(body) = before.strip_suffix(marker) {
1208 let open = body.rfind(marker)?;
1209 return valid_inner(&body[open + 2..]).then(|| (open..open + 2, body.len()..end, kind));
1210 }
1211 }
1212 if let Some(body) = before.strip_suffix('`') {
1213 let open = body.rfind('`')?;
1214 let usable = !body[open + 1..].trim().is_empty() && !body[..open].ends_with('`');
1215 return usable.then(|| (open..open + 1, body.len()..end, MarkKind::Code));
1216 }
1217 for marker in ['*', '_'] {
1218 if let Some(body) = before.strip_suffix(marker) {
1219 if body.ends_with(marker) {
1220 return None;
1221 }
1222 let open = body.rfind(marker)?;
1223 let opening_ok = !word_before(&body[..open]) && !body[..open].ends_with(marker);
1224 return (opening_ok && valid_inner(&body[open + 1..]))
1225 .then(|| (open..open + 1, body.len()..end, MarkKind::Italic));
1226 }
1227 }
1228 None
1229 }
1230
1231 fn edit_span(old: &str, new: &str, cursor: usize) -> (usize, usize, usize) {
1232 let prefix = old
1233 .char_indices()
1234 .zip(new.chars())
1235 .find(|((_, left), right)| left != right)
1236 .map_or(old.len().min(new.len()), |((index, _), _)| index);
1237 let prefix = {
1238 let mut prefix = prefix.min(old.len()).min(new.len());
1239 while !old.is_char_boundary(prefix) || !new.is_char_boundary(prefix) {
1240 prefix -= 1;
1241 }
1242 prefix
1243 };
1244 let suffix = old[prefix..]
1245 .chars()
1246 .rev()
1247 .zip(new[prefix..].chars().rev())
1248 .take_while(|(left, right)| left == right)
1249 .map(|(character, _)| character.len_utf8())
1250 .sum::<usize>();
1251 let (start, old_end, new_end) = (prefix, old.len() - suffix, new.len() - suffix);
1252 let cursor = cursor.min(new.len());
1253 let pure = old_end == start || new_end == start;
1254 if pure && new_end > cursor && new_end - cursor <= start {
1255 let slide = new_end - cursor;
1256 let (slid_start, slid_old_end, slid_new_end) =
1257 (start - slide, old_end - slide, new_end - slide);
1258 let boundaries = [slid_start, slid_old_end]
1259 .iter()
1260 .all(|offset| old.is_char_boundary(*offset))
1261 && [slid_start, slid_new_end]
1262 .iter()
1263 .all(|offset| new.is_char_boundary(*offset));
1264 if boundaries && new[slid_new_end..] == old[slid_old_end..] {
1265 return (slid_start, slid_old_end, slid_new_end);
1266 }
1267 }
1268 (start, old_end, new_end)
1269 }
1270
1271 fn joined_inline(lines: &[DraftLine]) -> String {
1272 lines
1273 .iter()
1274 .map(|line| inline_html(&line.content, &line.marks))
1275 .collect::<Vec<_>>()
1276 .join("<br>")
1277 }
1278
1279 fn inline_html(content: &str, marks: &[Mark]) -> String {
1280 let mut boundaries: Vec<usize> = marks
1281 .iter()
1282 .flat_map(|mark| [mark.range.start, mark.range.end])
1283 .chain([0, content.len()])
1284 .filter(|offset| *offset <= content.len())
1285 .collect();
1286 boundaries.sort_unstable();
1287 boundaries.dedup();
1288 let mut html = String::new();
1289 let mut open: Vec<&MarkKind> = Vec::new();
1290 for window in boundaries.windows(2) {
1291 let segment = window[0]..window[1];
1292 let mut active: Vec<&MarkKind> = marks
1293 .iter()
1294 .filter(|mark| mark.range.start <= segment.start && segment.end <= mark.range.end)
1295 .map(|mark| &mark.kind)
1296 .collect();
1297 active.sort();
1298 active.dedup();
1299 let common = open
1300 .iter()
1301 .zip(active.iter())
1302 .take_while(|(left, right)| left == right)
1303 .count();
1304 for kind in open.drain(common..).rev() {
1305 html.push_str(kind.close_tag());
1306 }
1307 for kind in &active[common..] {
1308 html.push_str(&kind.open_tag());
1309 }
1310 open.extend(active[common..].iter().copied());
1311 html.push_str(&escape_html(&content[segment]));
1312 }
1313 for kind in open.into_iter().rev() {
1314 html.push_str(kind.close_tag());
1315 }
1316 html
1317 }
1318
1319 fn list_html(lines: &[DraftLine]) -> String {
1320 let close = |ordered: bool| if ordered { "</li></ol>" } else { "</li></ul>" };
1321 let mut html = String::new();
1322 let mut open: Vec<(u8, bool)> = Vec::new();
1323 for line in lines {
1324 let ordered = matches!(line.kind, LineKind::Numbered(_));
1325 let depth = line
1326 .kind
1327 .depth()
1328 .min(open.last().map_or(0, |(depth, _)| depth + 1));
1329 while open
1330 .last()
1331 .is_some_and(|(open_depth, _)| *open_depth > depth)
1332 {
1333 let (_, was_ordered) = open.pop().unwrap_or_default();
1334 html.push_str(close(was_ordered));
1335 }
1336 match open.last().copied() {
1337 Some((open_depth, open_ordered)) if open_depth == depth && open_ordered == ordered => {
1338 html.push_str("</li>");
1339 }
1340 Some((open_depth, open_ordered)) if open_depth == depth => {
1341 html.push_str(close(open_ordered));
1342 open.pop();
1343 html.push_str(&list_open(ordered, line.number));
1344 open.push((depth, ordered));
1345 }
1346 _ => {
1347 html.push_str(&list_open(ordered, line.number));
1348 open.push((depth, ordered));
1349 }
1350 }
1351 html.push_str("<li>");
1352 html.push_str(&inline_html(&line.content, &line.marks));
1353 }
1354 for (_, ordered) in open.into_iter().rev() {
1355 html.push_str(close(ordered));
1356 }
1357 html
1358 }
1359
1360 fn list_open(ordered: bool, number: Option<u32>) -> String {
1361 match (ordered, number) {
1362 (false, _) => "<ul>".to_owned(),
1363 (true, Some(start)) if start != 1 => format!("<ol start=\"{start}\">"),
1364 (true, _) => "<ol>".to_owned(),
1365 }
1366 }
1367
1368 /// Text that `from_markdown` would format: pasting it converts.
1369 pub fn has_markdown(text: &str) -> bool {
1370 let draft = Draft::from_markdown(text);
1371 !draft.marks.is_empty() || draft.lines.iter().any(|kind| *kind != LineKind::Text)
1372 }
1373
1374 fn markdown_lines(text: &str) -> Vec<DraftLine> {
1375 let mut lines = Vec::new();
1376 let mut code: Option<Option<String>> = None;
1377 for raw in text.split('\n') {
1378 let raw = raw.strip_suffix('\r').unwrap_or(raw);
1379 let trimmed = raw.trim_start();
1380 if let Some(language) = &code {
1381 if trimmed.starts_with(FENCE) && trimmed.trim_end() == FENCE {
1382 code = None;
1383 } else {
1384 lines.push(DraftLine {
1385 kind: LineKind::Code(language.clone()),
1386 number: None,
1387 content: raw.to_owned(),
1388 marks: Vec::new(),
1389 });
1390 }
1391 continue;
1392 }
1393 if trimmed.starts_with(FENCE)
1394 && !trimmed[FENCE.len()..].contains('`')
1395 && let Some(language) = fence_language(trimmed)
1396 {
1397 code = Some(language);
1398 continue;
1399 }
1400 let indent: usize = raw[..raw.len() - trimmed.len()]
1401 .chars()
1402 .map(|character| if character == '\t' { 4 } else { 1 })
1403 .sum();
1404 let depth = ((indent / MARKDOWN_INDENT) as u8).min(MAX_DEPTH);
1405 let (kind, number, content) = if let Some(rest) = PASTED_BULLETS
1406 .iter()
1407 .find_map(|bullet| trimmed.strip_prefix(bullet))
1408 {
1409 (LineKind::Bullet(depth), None, rest)
1410 } else if let Some((length, number)) = numbered_marker(trimmed, 0) {
1411 (LineKind::Numbered(depth), Some(number), &trimmed[length..])
1412 } else if let Some(rest) = trimmed
1413 .strip_prefix("> ")
1414 .or_else(|| (trimmed == ">").then_some(""))
1415 {
1416 (LineKind::Quote, None, rest)
1417 } else {
1418 (LineKind::Text, None, raw)
1419 };
1420 let (content, marks) = parse_inline(content);
1421 lines.push(DraftLine {
1422 kind,
1423 number,
1424 content,
1425 marks,
1426 });
1427 }
1428 lines
1429 }
1430
1431 fn parse_inline(source: &str) -> (String, Vec<Mark>) {
1432 let mut text = String::with_capacity(source.len());
1433 let mut marks = Vec::new();
1434 parse_into(source, &mut text, &mut marks);
1435 (text, marks)
1436 }
1437
1438 fn parse_into(source: &str, text: &mut String, marks: &mut Vec<Mark>) {
1439 let mut rest = source;
1440 let mut previous: Option<char> = None;
1441 while let Some(character) = rest.chars().next() {
1442 if let Some((inner, consumed, kind)) = inline_at(rest, previous) {
1443 let start = text.len();
1444 if kind == MarkKind::Code {
1445 text.push_str(inner);
1446 } else {
1447 parse_into(inner, text, marks);
1448 }
1449 marks.push(Mark {
1450 range: start..text.len(),
1451 kind,
1452 });
1453 previous = rest[..consumed].chars().next_back();
1454 rest = &rest[consumed..];
1455 continue;
1456 }
1457 text.push(character);
1458 previous = Some(character);
1459 rest = &rest[character.len_utf8()..];
1460 }
1461 }
1462
1463 /// A format starting at the beginning of `rest`: its inner text, the bytes it spans, its kind.
1464 fn inline_at(rest: &str, previous: Option<char>) -> Option<(&str, usize, MarkKind)> {
1465 if let Some(after) = rest.strip_prefix('`') {
1466 let end = after.find('`')?;
1467 let inner = &after[..end];
1468 return (!inner.trim().is_empty()).then_some((inner, end + 2, MarkKind::Code));
1469 }
1470 if rest.starts_with('[') {
1471 let captures = LINK_AT.captures(rest)?;
1472 let label = captures.get(1)?;
1473 return Some((
1474 label.as_str(),
1475 captures.get(0)?.end(),
1476 MarkKind::Link(captures[2].to_owned()),
1477 ));
1478 }
1479 for (marker, kind) in [("**", MarkKind::Bold), ("~~", MarkKind::Strike)] {
1480 if let Some(after) = rest.strip_prefix(marker) {
1481 let end = after.find(marker)?;
1482 let inner = &after[..end];
1483 return valid_inner(inner).then_some((inner, end + 4, kind));
1484 }
1485 }
1486 for marker in ['*', '_'] {
1487 let Some(after) = rest.strip_prefix(marker) else {
1488 continue;
1489 };
1490 if previous.is_some_and(char::is_alphanumeric) || after.starts_with(marker) {
1491 return None;
1492 }
1493 let end = after.find(marker)?;
1494 let inner = &after[..end];
1495 let followed_by_word = after[end + 1..]
1496 .chars()
1497 .next()
1498 .is_some_and(char::is_alphanumeric);
1499 return (valid_inner(inner) && !followed_by_word).then_some((
1500 inner,
1501 end + 2,
1502 MarkKind::Italic,
1503 ));
1504 }
1505 None
1506 }
1507
1508 #[derive(Default)]
1509 struct SpanLines {
1510 lines: Vec<DraftLine>,
1511 open: bool,
1512 }
1513
1514 impl SpanLines {
1515 fn start_line(&mut self, kind: &LineKind, number: Option<u32>) {
1516 self.lines.push(DraftLine {
1517 kind: kind.clone(),
1518 number,
1519 content: String::new(),
1520 marks: Vec::new(),
1521 });
1522 self.open = true;
1523 }
1524
1525 fn append(&mut self, text: &str, kind: &LineKind, marks: &[MarkKind]) {
1526 for (index, piece) in text.split('\n').enumerate() {
1527 if index > 0 || !self.open {
1528 self.start_line(kind, None);
1529 }
1530 let Some(line) = self.lines.last_mut() else {
1531 continue;
1532 };
1533 let start = line.content.len();
1534 line.content.push_str(piece);
1535 let end = line.content.len();
1536 if end > start {
1537 line.marks.extend(marks.iter().map(|kind| Mark {
1538 range: start..end,
1539 kind: kind.clone(),
1540 }));
1541 }
1542 }
1543 }
1544
1545 fn walk(&mut self, spans: &[Span], kind: &LineKind, marks: &[MarkKind]) {
1546 let with = |extra: MarkKind| {
1547 let mut marks = marks.to_vec();
1548 marks.push(extra);
1549 marks
1550 };
1551 for (index, span) in spans.iter().enumerate() {
1552 let block_follows = matches!(
1553 spans.get(index + 1),
1554 Some(
1555 Span::List { .. }
1556 | Span::BlockQuote(_)
1557 | Span::CodeBlock { .. }
1558 | Span::Heading { .. }
1559 | Span::Table { .. }
1560 )
1561 );
1562 match span {
1563 Span::Text(text) => self.append(text, kind, marks),
1564 Span::Bold(children) => self.walk(children, kind, &with(MarkKind::Bold)),
1565 Span::Italic(children) => self.walk(children, kind, &with(MarkKind::Italic)),
1566 Span::Strike(children) => self.walk(children, kind, &with(MarkKind::Strike)),
1567 Span::Underline(children) => self.walk(children, kind, &with(MarkKind::Underline)),
1568 Span::Colored { children, .. } => self.walk(children, kind, marks),
1569 Span::Code(text) => self.append(text, kind, &with(MarkKind::Code)),
1570 Span::Link { url, children } => {
1571 self.walk(children, kind, &with(MarkKind::Link(url.clone())))
1572 }
1573 Span::Mention { name } => {
1574 self.append(&format!("@{}", name.trim_start_matches('@')), kind, marks)
1575 }
1576 Span::LineBreak | Span::Rule if !self.open || block_follows => {}
1577 Span::LineBreak | Span::Rule => {
1578 let continued = match kind {
1579 LineKind::Quote | LineKind::Code(_) => kind.clone(),
1580 _ => LineKind::Text,
1581 };
1582 self.start_line(&continued, None);
1583 }
1584 Span::Heading { children, .. } => {
1585 self.start_line(&LineKind::Text, None);
1586 self.walk(children, &LineKind::Text, &with(MarkKind::Bold));
1587 self.open = false;
1588 }
1589 Span::CodeBlock { language, code } => {
1590 let code_kind = LineKind::Code(language.clone());
1591 for line in code.trim_end_matches('\n').split('\n') {
1592 self.start_line(&code_kind, None);
1593 self.append(line, &code_kind, &[]);
1594 }
1595 self.open = false;
1596 }
1597 Span::BlockQuote(children) => {
1598 self.start_line(&LineKind::Quote, None);
1599 self.walk(children, &LineKind::Quote, marks);
1600 self.open = false;
1601 }
1602 Span::List {
1603 ordered,
1604 start,
1605 items,
1606 } => {
1607 let depth = if kind.is_list() {
1608 (kind.depth() + 1).min(MAX_DEPTH)
1609 } else {
1610 0
1611 };
1612 let item_kind = if *ordered {
1613 LineKind::Numbered(depth)
1614 } else {
1615 LineKind::Bullet(depth)
1616 };
1617 for (position, item) in items.iter().enumerate() {
1618 let number = (position == 0).then_some(*start);
1619 self.start_line(&item_kind, number);
1620 self.walk(item, &item_kind, marks);
1621 }
1622 self.open = false;
1623 }
1624 Span::Table { rows, .. } => {
1625 for row in rows {
1626 self.start_line(&LineKind::Text, None);
1627 for (position, cell) in row.iter().enumerate() {
1628 if position > 0 {
1629 self.append(" | ", &LineKind::Text, &[]);
1630 }
1631 self.walk(cell, &LineKind::Text, marks);
1632 }
1633 }
1634 self.open = false;
1635 }
1636 Span::Image { .. } | Span::Quote(_) => {}
1637 }
1638 }
1639 }
1640
1641 fn finish(mut self) -> Vec<DraftLine> {
1642 let blank =
1643 |line: &DraftLine| line.kind == LineKind::Text && line.content.trim().is_empty();
1644 while self.lines.len() > 1 && self.lines.last().is_some_and(blank) {
1645 self.lines.pop();
1646 }
1647 while self.lines.len() > 1 && self.lines.first().is_some_and(blank) {
1648 self.lines.remove(0);
1649 }
1650 if self.lines.is_empty() {
1651 self.lines.push(DraftLine::text(""));
1652 }
1653 self.lines
1654 }
1655 }
1656
1657 #[cfg(test)]
1658 mod tests {
1659 use super::*;
1660 use crate::html_to_spans;
1661
1662 fn typed(draft: &mut Draft, text: &str) {
1663 let mut typing: Option<TypingStyle> = None;
1664 for character in text.chars() {
1665 let cursor = draft.text().len();
1666 let mut next = draft.text().to_owned();
1667 next.push(character);
1668 let cursor = draft.apply_edit(&next, cursor + character.len_utf8(), typing.as_ref());
1669 typing = draft.convert_typed(cursor).map(|(_, style)| style);
1670 draft.take_edits();
1671 }
1672 }
1673
1674 fn typed_draft(text: &str) -> Draft {
1675 let mut draft = Draft::default();
1676 typed(&mut draft, text);
1677 draft
1678 }
1679
1680 fn mark(range: Range<usize>, kind: MarkKind) -> Mark {
1681 Mark { range, kind }
1682 }
1683
1684 #[test]
1685 fn typed_markdown_becomes_formatting() {
1686 let draft = typed_draft("a **bold** and *it* or _it_ ~~gone~~ `code`");
1687 assert_eq!(draft.text(), "a bold and it or it gone code");
1688 assert_eq!(
1689 draft.marks(),
1690 [
1691 mark(2..6, MarkKind::Bold),
1692 mark(11..13, MarkKind::Italic),
1693 mark(17..19, MarkKind::Italic),
1694 mark(20..24, MarkKind::Strike),
1695 mark(25..29, MarkKind::Code),
1696 ]
1697 );
1698 }
1699
1700 #[test]
1701 fn typed_link_keeps_the_label_and_carries_the_url() {
1702 let draft = typed_draft("see [docs](https://example.com)");
1703 assert_eq!(draft.text(), "see docs");
1704 assert_eq!(
1705 draft.marks(),
1706 [mark(4..8, MarkKind::Link("https://example.com".into()))]
1707 );
1708 }
1709
1710 #[test]
1711 fn snake_case_and_spaced_stars_stay_text() {
1712 assert_eq!(typed_draft("snake_case_name").text(), "snake_case_name");
1713 assert_eq!(typed_draft("2 * 3 * 4").text(), "2 * 3 * 4");
1714 assert!(typed_draft("a** b**").marks().is_empty());
1715 }
1716
1717 #[test]
1718 fn typing_at_the_end_of_bold_continues_it_but_not_after_a_link() {
1719 let mut draft = Draft::plain("b");
1720 draft.toggle(0..1, MarkKind::Bold);
1721 typed(&mut draft, "x");
1722 assert_eq!(draft.marks(), [mark(0..2, MarkKind::Bold)]);
1723 let converted = typed_draft("**b**x");
1724 assert_eq!(converted.marks(), [mark(0..1, MarkKind::Bold)]);
1725 let mut linked = typed_draft("[a](u)");
1726 typed(&mut linked, "b");
1727 assert_eq!(linked.marks(), [mark(0..1, MarkKind::Link("u".into()))]);
1728 }
1729
1730 #[test]
1731 fn typing_style_switches_bold_on_and_off_for_the_next_text() {
1732 let mut draft = Draft::plain("ab");
1733 let typing = TypingStyle {
1734 at: 2,
1735 add: vec![MarkKind::Bold],
1736 remove: Vec::new(),
1737 };
1738 draft.apply_edit("abc", 3, Some(&typing));
1739 assert_eq!(draft.marks(), [mark(2..3, MarkKind::Bold)]);
1740 let off = TypingStyle {
1741 at: 3,
1742 add: Vec::new(),
1743 remove: vec![MarkKind::Bold],
1744 };
1745 draft.apply_edit("abcd", 4, Some(&off));
1746 assert_eq!(draft.marks(), [mark(2..3, MarkKind::Bold)]);
1747 }
1748
1749 #[test]
1750 fn toggle_on_a_mixed_selection_formats_all_then_clears() {
1751 let mut draft = Draft::plain("hello world");
1752 draft.toggle(0..5, MarkKind::Bold);
1753 assert_eq!(draft.state(0..11, &MarkKind::Bold), FormatState::Mixed);
1754 draft.toggle(0..11, MarkKind::Bold);
1755 assert_eq!(draft.state(0..11, &MarkKind::Bold), FormatState::On);
1756 draft.toggle(0..11, MarkKind::Bold);
1757 assert_eq!(draft.state(0..11, &MarkKind::Bold), FormatState::Off);
1758 assert!(draft.marks().is_empty());
1759 }
1760
1761 #[test]
1762 fn deleting_inside_and_across_marks_shifts_and_clips() {
1763 let mut draft = Draft::plain("aa bold cc");
1764 draft.toggle(3..7, MarkKind::Bold);
1765 draft.apply_edit("aa bld cc", 4, None);
1766 assert_eq!(draft.marks(), [mark(3..6, MarkKind::Bold)]);
1767 draft.apply_edit("ald cc", 1, None);
1768 assert_eq!(draft.marks(), [mark(1..3, MarkKind::Bold)]);
1769 draft.apply_edit("XXald cc", 2, None);
1770 assert_eq!(draft.marks(), [mark(3..5, MarkKind::Bold)]);
1771 }
1772
1773 #[test]
1774 fn repeated_characters_are_attributed_to_the_cursor() {
1775 let mut draft = Draft::plain("aa");
1776 draft.toggle(0..1, MarkKind::Bold);
1777 draft.apply_edit("aaa", 2, None);
1778 assert_eq!(draft.marks(), [mark(0..2, MarkKind::Bold)]);
1779 }
1780
1781 #[test]
1782 fn list_shortcuts_turn_lines_into_items() {
1783 let draft = typed_draft("- one");
1784 assert_eq!(draft.text(), "• one");
1785 assert_eq!(draft.lines(), [LineKind::Bullet(0)]);
1786 let numbered = typed_draft("1. one");
1787 assert_eq!(numbered.text(), "1. one");
1788 assert_eq!(numbered.lines(), [LineKind::Numbered(0)]);
1789 let quote = typed_draft("> said");
1790 assert_eq!(quote.text(), format!("{QUOTE_MARKER}said"));
1791 assert_eq!(quote.lines(), [LineKind::Quote]);
1792 }
1793
1794 #[test]
1795 fn enter_continues_a_list_and_ends_it_on_an_empty_item() {
1796 let mut draft = typed_draft("1. one");
1797 let cursor = draft.break_line(draft.text().len(), false).unwrap();
1798 assert_eq!(draft.text(), "1. one\n2. ");
1799 assert_eq!(cursor, draft.text().len());
1800 typed(&mut draft, "two");
1801 let cursor = draft.break_line(draft.text().len(), false).unwrap();
1802 let cursor = draft.break_line(cursor, false).unwrap();
1803 assert_eq!(draft.text(), "1. one\n2. two\n");
1804 assert_eq!(cursor, draft.text().len());
1805 assert_eq!(draft.lines()[2], LineKind::Text);
1806 assert_eq!(Draft::plain("x").break_line(1, false), None);
1807 }
1808
1809 #[test]
1810 fn enter_in_the_middle_of_an_item_splits_it_and_renumbers() {
1811 let mut draft = Draft::from_markdown("1. ab\n2. c");
1812 draft.break_line(4, false).unwrap();
1813 assert_eq!(draft.text(), "1. a\n2. b\n3. c");
1814 let edits = draft.take_edits();
1815 assert_eq!(map_offset(&edits, 4), 8);
1816 }
1817
1818 #[test]
1819 fn tab_nests_and_shift_tab_lifts_list_items() {
1820 let mut draft = Draft::from_markdown("- a\n- b");
1821 assert!(draft.indent(6..6, false));
1822 assert_eq!(draft.lines(), [LineKind::Bullet(0), LineKind::Bullet(1)]);
1823 assert_eq!(draft.text(), format!("• a\n{INDENT}◦ b"));
1824 assert!(draft.indent(draft.text().len()..draft.text().len(), true));
1825 assert!(draft.indent(draft.text().len()..draft.text().len(), true));
1826 assert_eq!(draft.text(), "• a\nb");
1827 assert!(!Draft::plain("x").indent(0..0, false));
1828 }
1829
1830 #[test]
1831 fn nested_numbering_counts_per_level() {
1832 let draft = Draft::from_markdown("1. a\n 1. x\n 2. y\n2. b");
1833 assert_eq!(
1834 draft.text(),
1835 format!("1. a\n{INDENT}1. x\n{INDENT}2. y\n2. b")
1836 );
1837 }
1838
1839 #[test]
1840 fn backspace_at_an_item_start_drops_the_bullet() {
1841 let mut draft = Draft::from_markdown("- a");
1842 let cursor = draft.backspace_at_start(bullet_marker(0).len()).unwrap();
1843 assert_eq!((draft.text(), cursor), ("a", 0));
1844 assert_eq!(draft.lines(), [LineKind::Text]);
1845 }
1846
1847 #[test]
1848 fn typing_before_a_bullet_lands_after_it() {
1849 let mut draft = Draft::from_markdown("- a");
1850 let marker = bullet_marker(0);
1851 let cursor = draft.apply_edit(&format!("x{marker}a"), 1, None);
1852 assert_eq!(draft.text(), format!("{marker}xa"));
1853 assert_eq!(cursor, marker.len() + 1);
1854 assert_eq!(
1855 draft.take_edits(),
1856 [
1857 (0..1, String::new()),
1858 (marker.len() + 1..marker.len() + 1, "x".to_owned())
1859 ]
1860 );
1861 }
1862
1863 #[test]
1864 fn a_damaged_marker_turns_the_line_into_text() {
1865 let mut draft = Draft::from_markdown("- a");
1866 draft.apply_edit("•a", 1, None);
1867 assert_eq!(draft.lines(), [LineKind::Text]);
1868 }
1869
1870 #[test]
1871 fn fence_and_enter_open_a_code_block_that_enter_continues() {
1872 let mut draft = typed_draft("```rust");
1873 let cursor = draft.break_line(draft.text().len(), false).unwrap();
1874 assert_eq!((draft.text(), cursor), ("", 0));
1875 assert_eq!(draft.lines(), [LineKind::Code(Some("rust".into()))]);
1876 typed(&mut draft, "fn x() {}");
1877 let cursor = draft.break_line(draft.text().len(), false).unwrap();
1878 assert_eq!(draft.lines().len(), 2);
1879 assert_eq!(draft.break_line(cursor, false), Some(cursor));
1880 assert_eq!(draft.lines()[1], LineKind::Text);
1881 assert_eq!(
1882 draft.to_html(),
1883 "<pre class=\"language-rust\">fn x() {}</pre>"
1884 );
1885 }
1886
1887 #[test]
1888 fn markdown_inside_code_stays_literal() {
1889 let mut draft = typed_draft("```");
1890 let cursor = draft.break_line(3, false).unwrap();
1891 assert_eq!(cursor, 0);
1892 typed(&mut draft, "a **b**");
1893 assert_eq!(draft.text(), "a **b**");
1894 assert!(draft.marks().is_empty());
1895 }
1896
1897 #[test]
1898 fn html_nests_overlapping_marks_and_escapes() {
1899 let mut draft = Draft::plain("a<b & c");
1900 draft.toggle(0..4, MarkKind::Bold);
1901 draft.toggle(2..7, MarkKind::Italic);
1902 assert_eq!(draft.to_html(), "<b>a&lt;<i>b </i></b><i>&amp; c</i>");
1903 }
1904
1905 #[test]
1906 fn html_covers_every_format() {
1907 let draft = Draft::from_markdown(
1908 "**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```",
1909 );
1910 let mut underlined = draft.clone();
1911 underlined.toggle(0..1, MarkKind::Underline);
1912 assert_eq!(
1913 underlined.to_html(),
1914 "<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>\
1915 <blockquote>q1<br>q2</blockquote>\
1916 <ul><li>a<ul><li>b</li></ul></li></ul>\
1917 <ol><li>x</li><li>y</li></ol>\
1918 <pre class=\"language-py\">print(1)</pre>"
1919 );
1920 }
1921
1922 #[test]
1923 fn ordered_lists_keep_their_start() {
1924 let draft = Draft::from_markdown("3. c\n4. d");
1925 assert_eq!(draft.to_html(), "<ol start=\"3\"><li>c</li><li>d</li></ol>");
1926 }
1927
1928 #[test]
1929 fn spans_round_trip_through_html() {
1930 let source = Draft::from_markdown(
1931 "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",
1932 );
1933 let back = Draft::from_spans(&html_to_spans(&source.to_html()));
1934 assert_eq!(back.text(), source.text());
1935 assert_eq!(back.lines(), source.lines());
1936 assert_eq!(back.marks(), source.marks());
1937 }
1938
1939 #[test]
1940 fn mentions_from_html_come_back_as_at_text() {
1941 let draft = Draft::from_spans(&html_to_spans("hi <at id=\"0\">Ada</at> <b>now</b>"));
1942 assert_eq!(draft.text(), "hi @Ada now");
1943 assert_eq!(draft.marks(), [mark(8..11, MarkKind::Bold)]);
1944 }
1945
1946 #[test]
1947 fn pasted_markdown_is_detected() {
1948 assert!(has_markdown("see **this**"));
1949 assert!(has_markdown("- a\n- b"));
1950 assert!(has_markdown("```\nx\n```"));
1951 assert!(!has_markdown("plain text, 2*3=6 and snake_case"));
1952 }
1953
1954 #[test]
1955 fn slices_carry_formatting_into_another_draft() {
1956 let source = Draft::from_markdown("intro **bold**\n- one\n- two");
1957 let end = source.text().len();
1958 let fragment = source.slice(6..end);
1959 assert_eq!(fragment[0].kind, LineKind::Text);
1960 assert_eq!(fragment[1].kind, LineKind::Bullet(0));
1961 let mut target = Draft::plain("x ");
1962 let cursor = target.insert_lines(2..2, &fragment);
1963 assert_eq!(target.text(), "x bold\n• one\n• two");
1964 assert_eq!(cursor, target.text().len());
1965 assert_eq!(target.marks(), [mark(2..6, MarkKind::Bold)]);
1966 assert_eq!(
1967 target.lines()[1..],
1968 [LineKind::Bullet(0), LineKind::Bullet(0)]
1969 );
1970 }
1971
1972 #[test]
1973 fn journal_merges_edits_into_ranges_of_the_old_text() {
1974 let mut draft = Draft::plain("a **b** c");
1975 draft.splice(5..7, "", &[]);
1976 draft.splice(2..4, "", &[]);
1977 draft.splice(0..0, "X", &[]);
1978 let edits = draft.take_edits();
1979 assert_eq!(
1980 edits,
1981 [
1982 (0..0, "X".to_owned()),
1983 (2..4, String::new()),
1984 (5..7, String::new())
1985 ]
1986 );
1987 assert_eq!(
1988 reverse_edits(&edits, "a **b** c")[1],
1989 (3..3, "**".to_owned())
1990 );
1991 let mut touching = Draft::plain("abc");
1992 touching.splice(1..2, "XY", &[]);
1993 touching.splice(3..3, "Z", &[]);
1994 assert_eq!(touching.take_edits(), [(1..2, "XYZ".to_owned())]);
1995 }
1996
1997 #[test]
1998 fn trimming_drops_blank_lines_and_outer_spaces() {
1999 let mut draft = Draft::plain("\n hi **x** \n\n");
2000 draft.toggle(6..11, MarkKind::Bold);
2001 let trimmed = draft.trimmed();
2002 assert_eq!(trimmed.text(), "hi **x**");
2003 assert_eq!(trimmed.marks(), [mark(3..8, MarkKind::Bold)]);
2004 }
2005
2006 #[test]
2007 fn toolbar_line_toggles_apply_to_every_selected_line() {
2008 let mut draft = Draft::plain("a\nb");
2009 draft.toggle_lines(0..3, LineKind::Numbered(0));
2010 assert_eq!(draft.text(), "1. a\n2. b");
2011 assert_eq!(
2012 draft.line_state(0..4, &LineKind::Numbered(0)),
2013 FormatState::On
2014 );
2015 draft.toggle_lines(0..9, LineKind::Bullet(0));
2016 assert_eq!(draft.text(), "• a\n• b");
2017 let end = draft.text().len();
2018 draft.toggle_lines(0..end, LineKind::Bullet(0));
2019 assert_eq!(draft.text(), "a\nb");
2020 }
2021
2022 #[test]
2023 fn links_are_set_replaced_and_removed() {
2024 let mut draft = Draft::plain("go here");
2025 draft.set_link(3..7, "https://a.test");
2026 assert_eq!(draft.link_in(4..4), Some("https://a.test".into()));
2027 draft.set_link(3..7, "");
2028 assert!(draft.marks().is_empty());
2029 let end = draft.insert_link(7, " https://b.test", "https://b.test");
2030 assert_eq!(end, draft.text().len());
2031 }
2032 }
@@ -0,0 +1,2032 @@
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 line_was_empty = self.lines[index] == LineKind::Text && content.is_empty();
761 let joined = lines
762 .iter()
763 .map(|line| line.content.as_str())
764 .collect::<Vec<_>>()
765 .join("\n");
766 self.splice(range.clone(), &joined, &[]);
767 let mut offset = range.start;
768 for line in lines {
769 for mark in &line.marks {
770 self.add_mark(
771 offset + mark.range.start..offset + mark.range.end,
772 mark.kind.clone(),
773 );
774 }
775 offset += line.content.len() + 1;
776 }
777 for (position, line) in lines.iter().enumerate() {
778 let first_and_kept = position == 0 && !line_was_empty;
779 if first_and_kept || line.kind == self.lines[index + position] {
780 continue;
781 }
782 self.set_line_kind(index + position, line.kind.clone(), line.number, 0);
783 }
784 let last = index + lines.len().saturating_sub(1);
785 let end =
786 self.content_range(last).start + lines.last().map_or(0, |line| line.content.len());
787 self.repair(end)
788 }
789
790 /// Leading and trailing blank lines and spaces dropped.
791 pub fn trimmed(&self) -> Draft {
792 let mut lines = self.slice(0..self.text.len());
793 let blank =
794 |line: &DraftLine| line.kind == LineKind::Text && line.content.trim().is_empty();
795 while lines.len() > 1 && lines.first().is_some_and(blank) {
796 lines.remove(0);
797 }
798 while lines.len() > 1 && lines.last().is_some_and(blank) {
799 lines.pop();
800 }
801 if let Some(first) = lines.first_mut().filter(|line| line.kind == LineKind::Text) {
802 first.trim_start();
803 }
804 if let Some(last) = lines
805 .last_mut()
806 .filter(|line| !matches!(line.kind, LineKind::Code(_)))
807 {
808 last.trim_end();
809 }
810 Draft::from_lines(&lines)
811 }
812
813 /// Teams chat HTML.
814 pub fn to_html(&self) -> String {
815 let lines = self.slice(0..self.text.len());
816 let mut html = String::new();
817 let mut index = 0;
818 while index < lines.len() {
819 let kind = &lines[index].kind;
820 let run_end = index
821 + lines[index..]
822 .iter()
823 .take_while(|line| match kind {
824 LineKind::Code(_) => line.kind == *kind,
825 _ if kind.is_list() => line.kind.is_list(),
826 _ => line.kind.same_format(kind),
827 })
828 .count();
829 let run = &lines[index..run_end];
830 match kind {
831 LineKind::Text => html.push_str(&joined_inline(run)),
832 LineKind::Quote => {
833 html.push_str("<blockquote>");
834 html.push_str(&joined_inline(run));
835 html.push_str("</blockquote>");
836 }
837 LineKind::Code(language) => {
838 match language {
839 Some(language) => html.push_str(&format!(
840 "<pre class=\"language-{}\">",
841 escape_html(language)
842 )),
843 None => html.push_str("<pre>"),
844 }
845 let code = run
846 .iter()
847 .map(|line| escape_html(&line.content))
848 .collect::<Vec<_>>()
849 .join("\n");
850 html.push_str(&code);
851 html.push_str("</pre>");
852 }
853 _ => html.push_str(&list_html(run)),
854 }
855 index = run_end;
856 }
857 html
858 }
859
860 fn style_for_insertion(&self, start: usize, old_end: usize) -> Vec<MarkKind> {
861 let mut kinds: Vec<MarkKind> = self
862 .marks
863 .iter()
864 .filter(|mark| {
865 let range = &mark.range;
866 if old_end > start {
867 range.start <= start && start < range.end
868 } else {
869 (range.start < start && start < range.end)
870 || (range.start < start
871 && range.end == start
872 && mark.kind.continues_at_end())
873 }
874 })
875 .map(|mark| mark.kind.clone())
876 .collect();
877 kinds.sort();
878 kinds.dedup();
879 kinds
880 }
881
882 fn content_parts(&self, range: Range<usize>) -> Vec<Range<usize>> {
883 (self.line_at(range.start)..=self.line_at(range.end))
884 .map(|index| {
885 let content = self.content_range(index);
886 content.start.max(range.start)..content.end.min(range.end)
887 })
888 .filter(|part| !part.is_empty())
889 .collect()
890 }
891
892 fn add_mark(&mut self, range: Range<usize>, kind: MarkKind) {
893 if !range.is_empty() {
894 self.marks.push(Mark { range, kind });
895 self.normalize_marks();
896 }
897 }
898
899 fn remove_marks(&mut self, range: Range<usize>, kind: &MarkKind) {
900 let mut kept = Vec::with_capacity(self.marks.len());
901 for mark in std::mem::take(&mut self.marks) {
902 if !mark.kind.same_format(kind) || !overlaps(&mark.range, &range) {
903 kept.push(mark);
904 continue;
905 }
906 if mark.range.start < range.start {
907 kept.push(Mark {
908 range: mark.range.start..range.start,
909 kind: mark.kind.clone(),
910 });
911 }
912 if mark.range.end > range.end {
913 kept.push(Mark {
914 range: range.end..mark.range.end,
915 kind: mark.kind,
916 });
917 }
918 }
919 self.marks = kept;
920 self.normalize_marks();
921 }
922
923 fn normalize_marks(&mut self) {
924 let length = self.text.len();
925 let mut marks: Vec<Mark> = std::mem::take(&mut self.marks)
926 .into_iter()
927 .map(|mark| Mark {
928 range: mark.range.start.min(length)..mark.range.end.min(length),
929 kind: mark.kind,
930 })
931 .filter(|mark| !mark.range.is_empty())
932 .collect();
933 marks.sort_by(|left, right| {
934 left.kind
935 .cmp(&right.kind)
936 .then(left.range.start.cmp(&right.range.start))
937 });
938 let mut merged: Vec<Mark> = Vec::with_capacity(marks.len());
939 for mark in marks {
940 match merged.last_mut() {
941 Some(last) if last.kind == mark.kind && mark.range.start <= last.range.end => {
942 last.range.end = last.range.end.max(mark.range.end);
943 }
944 _ => merged.push(mark),
945 }
946 }
947 self.marks = merged;
948 }
949
950 fn splice(&mut self, range: Range<usize>, replacement: &str, kinds: &[MarkKind]) {
951 let (start, old_end) = (range.start, range.end);
952 let first_line = self.line_at(start);
953 let last_line = self.line_at(old_end);
954 let line_start = self.line_ranges()[first_line].start;
955 let breaks = replacement.matches('\n').count();
956 let kind = self.lines[first_line].clone();
957 let mut new_kinds = Vec::with_capacity(breaks + 1);
958 if breaks > 0 && start == line_start && old_end == start {
959 new_kinds.extend(std::iter::repeat_n(LineKind::Text, breaks));
960 new_kinds.push(kind);
961 } else {
962 let continued = match &kind {
963 LineKind::Code(language) => LineKind::Code(language.clone()),
964 _ => LineKind::Text,
965 };
966 new_kinds.push(kind);
967 new_kinds.extend(std::iter::repeat_n(continued, breaks));
968 }
969 self.lines.splice(first_line..=last_line, new_kinds);
970 self.text.replace_range(range.clone(), replacement);
971
972 let inserted = replacement.len();
973 let delta = inserted as isize - (old_end - start) as isize;
974 let shift = |position: usize| (position as isize + delta) as usize;
975 let map_start = |position: usize| {
976 if position < start {
977 position
978 } else if position >= old_end {
979 shift(position)
980 } else {
981 start + inserted
982 }
983 };
984 let map_end = |position: usize| {
985 if position <= start {
986 position
987 } else if position >= old_end {
988 shift(position)
989 } else {
990 start
991 }
992 };
993 for mark in &mut self.marks {
994 mark.range = map_start(mark.range.start)..map_end(mark.range.end);
995 }
996 if inserted > 0 {
997 let inserted_range = start..start + inserted;
998 let mut kept = Vec::with_capacity(self.marks.len() + kinds.len());
999 for mark in std::mem::take(&mut self.marks) {
1000 if !overlaps(&mark.range, &inserted_range) || kinds.contains(&mark.kind) {
1001 kept.push(mark);
1002 continue;
1003 }
1004 if mark.range.start < inserted_range.start {
1005 kept.push(Mark {
1006 range: mark.range.start..inserted_range.start,
1007 kind: mark.kind.clone(),
1008 });
1009 }
1010 if mark.range.end > inserted_range.end {
1011 kept.push(Mark {
1012 range: inserted_range.end..mark.range.end,
1013 kind: mark.kind,
1014 });
1015 }
1016 }
1017 kept.extend(kinds.iter().map(|kind| Mark {
1018 range: inserted_range.clone(),
1019 kind: kind.clone(),
1020 }));
1021 self.marks = kept;
1022 }
1023 self.normalize_marks();
1024 self.journal.record(range, inserted, &self.text);
1025 }
1026
1027 fn previous_number(&self, index: usize, depth: u8) -> Option<u32> {
1028 let ranges = self.line_ranges();
1029 for previous in (0..index).rev() {
1030 match &self.lines[previous] {
1031 LineKind::Numbered(previous_depth) if *previous_depth == depth => {
1032 return numbered_marker(&self.text[ranges[previous].clone()], depth)
1033 .map(|(_, number)| number);
1034 }
1035 kind if kind.is_list() && kind.depth() > depth => continue,
1036 _ => return None,
1037 }
1038 }
1039 None
1040 }
1041
1042 fn expected_marker(&self, index: usize, own_number: Option<u32>) -> String {
1043 let kind = &self.lines[index];
1044 let number = match kind {
1045 LineKind::Numbered(depth) => match self.previous_number(index, *depth) {
1046 Some(previous) => previous + 1,
1047 None => own_number
1048 .or_else(|| {
1049 let line = self.line_ranges()[index].clone();
1050 numbered_marker(&self.text[line], *depth).map(|(_, number)| number)
1051 })
1052 .unwrap_or(1),
1053 },
1054 _ => 1,
1055 };
1056 marker_text(kind, number)
1057 }
1058
1059 fn set_line_kind(
1060 &mut self,
1061 index: usize,
1062 kind: LineKind,
1063 number: Option<u32>,
1064 cursor: usize,
1065 ) -> usize {
1066 let marker = self.marker_range(index);
1067 self.lines[index] = kind;
1068 let expected = self.expected_marker(index, number);
1069 self.replace_marker(marker, &expected, cursor)
1070 }
1071
1072 fn replace_marker(&mut self, marker: Range<usize>, expected: &str, cursor: usize) -> usize {
1073 if self.text[marker.clone()] == *expected {
1074 return cursor;
1075 }
1076 self.splice(marker.clone(), expected, &[]);
1077 if cursor >= marker.end {
1078 cursor + expected.len() - marker.len()
1079 } else if cursor > marker.start {
1080 marker.start + expected.len()
1081 } else {
1082 cursor
1083 }
1084 }
1085
1086 /// Lines whose marker was edited away become text; numbered items are renumbered.
1087 fn repair(&mut self, mut cursor: usize) -> usize {
1088 for index in 0..self.lines.len() {
1089 let kind = self.lines[index].clone();
1090 if matches!(kind, LineKind::Text | LineKind::Code(_)) {
1091 continue;
1092 }
1093 let line = self.line_ranges()[index].clone();
1094 let expected = self.expected_marker(index, None);
1095 let current = &self.text[line.clone()];
1096 if current.starts_with(&expected) {
1097 continue;
1098 }
1099 match numbered_marker(current, kind.depth()) {
1100 Some((length, _)) if matches!(kind, LineKind::Numbered(_)) => {
1101 cursor =
1102 self.replace_marker(line.start..line.start + length, &expected, cursor);
1103 }
1104 _ => self.lines[index] = LineKind::Text,
1105 }
1106 }
1107 cursor
1108 }
1109}
1110
1111fn overlaps(left: &Range<usize>, right: &Range<usize>) -> bool {
1112 left.start < right.end && right.start < left.end
1113}
1114
1115fn bullet_marker(depth: u8) -> String {
1116 format!(
1117 "{}{} ",
1118 INDENT.repeat(depth as usize),
1119 BULLETS[depth as usize % BULLETS.len()]
1120 )
1121}
1122
1123fn marker_text(kind: &LineKind, number: u32) -> String {
1124 match kind {
1125 LineKind::Bullet(depth) => bullet_marker(*depth),
1126 LineKind::Numbered(depth) => format!("{}{number}. ", INDENT.repeat(*depth as usize)),
1127 LineKind::Quote => QUOTE_MARKER.to_owned(),
1128 LineKind::Text | LineKind::Code(_) => String::new(),
1129 }
1130}
1131
1132fn marker_len(kind: &LineKind, line: &str) -> usize {
1133 match kind {
1134 LineKind::Bullet(depth) => {
1135 let marker = bullet_marker(*depth);
1136 if line.starts_with(&marker) {
1137 marker.len()
1138 } else {
1139 0
1140 }
1141 }
1142 LineKind::Numbered(depth) => numbered_marker(line, *depth).map_or(0, |(length, _)| length),
1143 LineKind::Quote if line.starts_with(QUOTE_MARKER) => QUOTE_MARKER.len(),
1144 _ => 0,
1145 }
1146}
1147
1148/// Byte length and number of a `1. ` marker at `depth`.
1149fn numbered_marker(line: &str, depth: u8) -> Option<(usize, u32)> {
1150 let indent = INDENT.repeat(depth as usize);
1151 let rest = line.strip_prefix(indent.as_str())?;
1152 let digits = rest.bytes().take_while(u8::is_ascii_digit).count();
1153 if digits == 0 || digits > 9 || !rest[digits..].starts_with(". ") {
1154 return None;
1155 }
1156 Some((indent.len() + digits + 2, rest[..digits].parse().ok()?))
1157}
1158
1159fn line_shortcut(before: &str) -> Option<(LineKind, u32)> {
1160 match before {
1161 "- " | "* " => Some((LineKind::Bullet(0), 1)),
1162 "> " => Some((LineKind::Quote, 1)),
1163 _ => {
1164 let digits = before.strip_suffix(". ")?;
1165 let all_digits = !digits.is_empty()
1166 && digits.len() <= 9
1167 && digits.bytes().all(|byte| byte.is_ascii_digit());
1168 all_digits.then(|| (LineKind::Numbered(0), digits.parse().unwrap_or(1)))
1169 }
1170 }
1171}
1172
1173fn fence_language(line: &str) -> Option<Option<String>> {
1174 let info = line.trim().strip_prefix(FENCE)?;
1175 let valid = info
1176 .chars()
1177 .all(|character| character.is_alphanumeric() || "+#-_.".contains(character));
1178 valid.then(|| (!info.is_empty()).then(|| info.to_lowercase()))
1179}
1180
1181fn valid_inner(inner: &str) -> bool {
1182 !inner.is_empty()
1183 && !inner.starts_with(char::is_whitespace)
1184 && !inner.ends_with(char::is_whitespace)
1185}
1186
1187fn word_before(text: &str) -> bool {
1188 text.chars()
1189 .next_back()
1190 .is_some_and(|character| character.is_alphanumeric())
1191}
1192
1193/// The markers of a format closed by the last typed character, relative to `before`.
1194fn typed_inline(before: &str) -> Option<(Range<usize>, Range<usize>, MarkKind)> {
1195 let end = before.len();
1196 if before.ends_with(')') {
1197 let captures = TYPED_LINK.captures(before)?;
1198 let whole = captures.get(0)?;
1199 let label = captures.get(1)?;
1200 return Some((
1201 whole.start()..whole.start() + 1,
1202 label.end()..end,
1203 MarkKind::Link(captures[2].to_owned()),
1204 ));
1205 }
1206 for (marker, kind) in [("**", MarkKind::Bold), ("~~", MarkKind::Strike)] {
1207 if let Some(body) = before.strip_suffix(marker) {
1208 let open = body.rfind(marker)?;
1209 return valid_inner(&body[open + 2..]).then(|| (open..open + 2, body.len()..end, kind));
1210 }
1211 }
1212 if let Some(body) = before.strip_suffix('`') {
1213 let open = body.rfind('`')?;
1214 let usable = !body[open + 1..].trim().is_empty() && !body[..open].ends_with('`');
1215 return usable.then(|| (open..open + 1, body.len()..end, MarkKind::Code));
1216 }
1217 for marker in ['*', '_'] {
1218 if let Some(body) = before.strip_suffix(marker) {
1219 if body.ends_with(marker) {
1220 return None;
1221 }
1222 let open = body.rfind(marker)?;
1223 let opening_ok = !word_before(&body[..open]) && !body[..open].ends_with(marker);
1224 return (opening_ok && valid_inner(&body[open + 1..]))
1225 .then(|| (open..open + 1, body.len()..end, MarkKind::Italic));
1226 }
1227 }
1228 None
1229}
1230
1231fn edit_span(old: &str, new: &str, cursor: usize) -> (usize, usize, usize) {
1232 let prefix = old
1233 .char_indices()
1234 .zip(new.chars())
1235 .find(|((_, left), right)| left != right)
1236 .map_or(old.len().min(new.len()), |((index, _), _)| index);
1237 let prefix = {
1238 let mut prefix = prefix.min(old.len()).min(new.len());
1239 while !old.is_char_boundary(prefix) || !new.is_char_boundary(prefix) {
1240 prefix -= 1;
1241 }
1242 prefix
1243 };
1244 let suffix = old[prefix..]
1245 .chars()
1246 .rev()
1247 .zip(new[prefix..].chars().rev())
1248 .take_while(|(left, right)| left == right)
1249 .map(|(character, _)| character.len_utf8())
1250 .sum::<usize>();
1251 let (start, old_end, new_end) = (prefix, old.len() - suffix, new.len() - suffix);
1252 let cursor = cursor.min(new.len());
1253 let pure = old_end == start || new_end == start;
1254 if pure && new_end > cursor && new_end - cursor <= start {
1255 let slide = new_end - cursor;
1256 let (slid_start, slid_old_end, slid_new_end) =
1257 (start - slide, old_end - slide, new_end - slide);
1258 let boundaries = [slid_start, slid_old_end]
1259 .iter()
1260 .all(|offset| old.is_char_boundary(*offset))
1261 && [slid_start, slid_new_end]
1262 .iter()
1263 .all(|offset| new.is_char_boundary(*offset));
1264 if boundaries && new[slid_new_end..] == old[slid_old_end..] {
1265 return (slid_start, slid_old_end, slid_new_end);
1266 }
1267 }
1268 (start, old_end, new_end)
1269}
1270
1271fn joined_inline(lines: &[DraftLine]) -> String {
1272 lines
1273 .iter()
1274 .map(|line| inline_html(&line.content, &line.marks))
1275 .collect::<Vec<_>>()
1276 .join("<br>")
1277}
1278
1279fn inline_html(content: &str, marks: &[Mark]) -> String {
1280 let mut boundaries: Vec<usize> = marks
1281 .iter()
1282 .flat_map(|mark| [mark.range.start, mark.range.end])
1283 .chain([0, content.len()])
1284 .filter(|offset| *offset <= content.len())
1285 .collect();
1286 boundaries.sort_unstable();
1287 boundaries.dedup();
1288 let mut html = String::new();
1289 let mut open: Vec<&MarkKind> = Vec::new();
1290 for window in boundaries.windows(2) {
1291 let segment = window[0]..window[1];
1292 let mut active: Vec<&MarkKind> = marks
1293 .iter()
1294 .filter(|mark| mark.range.start <= segment.start && segment.end <= mark.range.end)
1295 .map(|mark| &mark.kind)
1296 .collect();
1297 active.sort();
1298 active.dedup();
1299 let common = open
1300 .iter()
1301 .zip(active.iter())
1302 .take_while(|(left, right)| left == right)
1303 .count();
1304 for kind in open.drain(common..).rev() {
1305 html.push_str(kind.close_tag());
1306 }
1307 for kind in &active[common..] {
1308 html.push_str(&kind.open_tag());
1309 }
1310 open.extend(active[common..].iter().copied());
1311 html.push_str(&escape_html(&content[segment]));
1312 }
1313 for kind in open.into_iter().rev() {
1314 html.push_str(kind.close_tag());
1315 }
1316 html
1317}
1318
1319fn list_html(lines: &[DraftLine]) -> String {
1320 let close = |ordered: bool| if ordered { "</li></ol>" } else { "</li></ul>" };
1321 let mut html = String::new();
1322 let mut open: Vec<(u8, bool)> = Vec::new();
1323 for line in lines {
1324 let ordered = matches!(line.kind, LineKind::Numbered(_));
1325 let depth = line
1326 .kind
1327 .depth()
1328 .min(open.last().map_or(0, |(depth, _)| depth + 1));
1329 while open
1330 .last()
1331 .is_some_and(|(open_depth, _)| *open_depth > depth)
1332 {
1333 let (_, was_ordered) = open.pop().unwrap_or_default();
1334 html.push_str(close(was_ordered));
1335 }
1336 match open.last().copied() {
1337 Some((open_depth, open_ordered)) if open_depth == depth && open_ordered == ordered => {
1338 html.push_str("</li>");
1339 }
1340 Some((open_depth, open_ordered)) if open_depth == depth => {
1341 html.push_str(close(open_ordered));
1342 open.pop();
1343 html.push_str(&list_open(ordered, line.number));
1344 open.push((depth, ordered));
1345 }
1346 _ => {
1347 html.push_str(&list_open(ordered, line.number));
1348 open.push((depth, ordered));
1349 }
1350 }
1351 html.push_str("<li>");
1352 html.push_str(&inline_html(&line.content, &line.marks));
1353 }
1354 for (_, ordered) in open.into_iter().rev() {
1355 html.push_str(close(ordered));
1356 }
1357 html
1358}
1359
1360fn list_open(ordered: bool, number: Option<u32>) -> String {
1361 match (ordered, number) {
1362 (false, _) => "<ul>".to_owned(),
1363 (true, Some(start)) if start != 1 => format!("<ol start=\"{start}\">"),
1364 (true, _) => "<ol>".to_owned(),
1365 }
1366}
1367
1368/// Text that `from_markdown` would format: pasting it converts.
1369pub fn has_markdown(text: &str) -> bool {
1370 let draft = Draft::from_markdown(text);
1371 !draft.marks.is_empty() || draft.lines.iter().any(|kind| *kind != LineKind::Text)
1372}
1373
1374fn markdown_lines(text: &str) -> Vec<DraftLine> {
1375 let mut lines = Vec::new();
1376 let mut code: Option<Option<String>> = None;
1377 for raw in text.split('\n') {
1378 let raw = raw.strip_suffix('\r').unwrap_or(raw);
1379 let trimmed = raw.trim_start();
1380 if let Some(language) = &code {
1381 if trimmed.starts_with(FENCE) && trimmed.trim_end() == FENCE {
1382 code = None;
1383 } else {
1384 lines.push(DraftLine {
1385 kind: LineKind::Code(language.clone()),
1386 number: None,
1387 content: raw.to_owned(),
1388 marks: Vec::new(),
1389 });
1390 }
1391 continue;
1392 }
1393 if trimmed.starts_with(FENCE)
1394 && !trimmed[FENCE.len()..].contains('`')
1395 && let Some(language) = fence_language(trimmed)
1396 {
1397 code = Some(language);
1398 continue;
1399 }
1400 let indent: usize = raw[..raw.len() - trimmed.len()]
1401 .chars()
1402 .map(|character| if character == '\t' { 4 } else { 1 })
1403 .sum();
1404 let depth = ((indent / MARKDOWN_INDENT) as u8).min(MAX_DEPTH);
1405 let (kind, number, content) = if let Some(rest) = PASTED_BULLETS
1406 .iter()
1407 .find_map(|bullet| trimmed.strip_prefix(bullet))
1408 {
1409 (LineKind::Bullet(depth), None, rest)
1410 } else if let Some((length, number)) = numbered_marker(trimmed, 0) {
1411 (LineKind::Numbered(depth), Some(number), &trimmed[length..])
1412 } else if let Some(rest) = trimmed
1413 .strip_prefix("> ")
1414 .or_else(|| (trimmed == ">").then_some(""))
1415 {
1416 (LineKind::Quote, None, rest)
1417 } else {
1418 (LineKind::Text, None, raw)
1419 };
1420 let (content, marks) = parse_inline(content);
1421 lines.push(DraftLine {
1422 kind,
1423 number,
1424 content,
1425 marks,
1426 });
1427 }
1428 lines
1429}
1430
1431fn parse_inline(source: &str) -> (String, Vec<Mark>) {
1432 let mut text = String::with_capacity(source.len());
1433 let mut marks = Vec::new();
1434 parse_into(source, &mut text, &mut marks);
1435 (text, marks)
1436}
1437
1438fn parse_into(source: &str, text: &mut String, marks: &mut Vec<Mark>) {
1439 let mut rest = source;
1440 let mut previous: Option<char> = None;
1441 while let Some(character) = rest.chars().next() {
1442 if let Some((inner, consumed, kind)) = inline_at(rest, previous) {
1443 let start = text.len();
1444 if kind == MarkKind::Code {
1445 text.push_str(inner);
1446 } else {
1447 parse_into(inner, text, marks);
1448 }
1449 marks.push(Mark {
1450 range: start..text.len(),
1451 kind,
1452 });
1453 previous = rest[..consumed].chars().next_back();
1454 rest = &rest[consumed..];
1455 continue;
1456 }
1457 text.push(character);
1458 previous = Some(character);
1459 rest = &rest[character.len_utf8()..];
1460 }
1461}
1462
1463/// A format starting at the beginning of `rest`: its inner text, the bytes it spans, its kind.
1464fn inline_at(rest: &str, previous: Option<char>) -> Option<(&str, usize, MarkKind)> {
1465 if let Some(after) = rest.strip_prefix('`') {
1466 let end = after.find('`')?;
1467 let inner = &after[..end];
1468 return (!inner.trim().is_empty()).then_some((inner, end + 2, MarkKind::Code));
1469 }
1470 if rest.starts_with('[') {
1471 let captures = LINK_AT.captures(rest)?;
1472 let label = captures.get(1)?;
1473 return Some((
1474 label.as_str(),
1475 captures.get(0)?.end(),
1476 MarkKind::Link(captures[2].to_owned()),
1477 ));
1478 }
1479 for (marker, kind) in [("**", MarkKind::Bold), ("~~", MarkKind::Strike)] {
1480 if let Some(after) = rest.strip_prefix(marker) {
1481 let end = after.find(marker)?;
1482 let inner = &after[..end];
1483 return valid_inner(inner).then_some((inner, end + 4, kind));
1484 }
1485 }
1486 for marker in ['*', '_'] {
1487 let Some(after) = rest.strip_prefix(marker) else {
1488 continue;
1489 };
1490 if previous.is_some_and(char::is_alphanumeric) || after.starts_with(marker) {
1491 return None;
1492 }
1493 let end = after.find(marker)?;
1494 let inner = &after[..end];
1495 let followed_by_word = after[end + 1..]
1496 .chars()
1497 .next()
1498 .is_some_and(char::is_alphanumeric);
1499 return (valid_inner(inner) && !followed_by_word).then_some((
1500 inner,
1501 end + 2,
1502 MarkKind::Italic,
1503 ));
1504 }
1505 None
1506}
1507
1508#[derive(Default)]
1509struct SpanLines {
1510 lines: Vec<DraftLine>,
1511 open: bool,
1512}
1513
1514impl SpanLines {
1515 fn start_line(&mut self, kind: &LineKind, number: Option<u32>) {
1516 self.lines.push(DraftLine {
1517 kind: kind.clone(),
1518 number,
1519 content: String::new(),
1520 marks: Vec::new(),
1521 });
1522 self.open = true;
1523 }
1524
1525 fn append(&mut self, text: &str, kind: &LineKind, marks: &[MarkKind]) {
1526 for (index, piece) in text.split('\n').enumerate() {
1527 if index > 0 || !self.open {
1528 self.start_line(kind, None);
1529 }
1530 let Some(line) = self.lines.last_mut() else {
1531 continue;
1532 };
1533 let start = line.content.len();
1534 line.content.push_str(piece);
1535 let end = line.content.len();
1536 if end > start {
1537 line.marks.extend(marks.iter().map(|kind| Mark {
1538 range: start..end,
1539 kind: kind.clone(),
1540 }));
1541 }
1542 }
1543 }
1544
1545 fn walk(&mut self, spans: &[Span], kind: &LineKind, marks: &[MarkKind]) {
1546 let with = |extra: MarkKind| {
1547 let mut marks = marks.to_vec();
1548 marks.push(extra);
1549 marks
1550 };
1551 for (index, span) in spans.iter().enumerate() {
1552 let block_follows = matches!(
1553 spans.get(index + 1),
1554 Some(
1555 Span::List { .. }
1556 | Span::BlockQuote(_)
1557 | Span::CodeBlock { .. }
1558 | Span::Heading { .. }
1559 | Span::Table { .. }
1560 )
1561 );
1562 match span {
1563 Span::Text(text) => self.append(text, kind, marks),
1564 Span::Bold(children) => self.walk(children, kind, &with(MarkKind::Bold)),
1565 Span::Italic(children) => self.walk(children, kind, &with(MarkKind::Italic)),
1566 Span::Strike(children) => self.walk(children, kind, &with(MarkKind::Strike)),
1567 Span::Underline(children) => self.walk(children, kind, &with(MarkKind::Underline)),
1568 Span::Colored { children, .. } => self.walk(children, kind, marks),
1569 Span::Code(text) => self.append(text, kind, &with(MarkKind::Code)),
1570 Span::Link { url, children } => {
1571 self.walk(children, kind, &with(MarkKind::Link(url.clone())))
1572 }
1573 Span::Mention { name } => {
1574 self.append(&format!("@{}", name.trim_start_matches('@')), kind, marks)
1575 }
1576 Span::LineBreak | Span::Rule if !self.open || block_follows => {}
1577 Span::LineBreak | Span::Rule => {
1578 let continued = match kind {
1579 LineKind::Quote | LineKind::Code(_) => kind.clone(),
1580 _ => LineKind::Text,
1581 };
1582 self.start_line(&continued, None);
1583 }
1584 Span::Heading { children, .. } => {
1585 self.start_line(&LineKind::Text, None);
1586 self.walk(children, &LineKind::Text, &with(MarkKind::Bold));
1587 self.open = false;
1588 }
1589 Span::CodeBlock { language, code } => {
1590 let code_kind = LineKind::Code(language.clone());
1591 for line in code.trim_end_matches('\n').split('\n') {
1592 self.start_line(&code_kind, None);
1593 self.append(line, &code_kind, &[]);
1594 }
1595 self.open = false;
1596 }
1597 Span::BlockQuote(children) => {
1598 self.start_line(&LineKind::Quote, None);
1599 self.walk(children, &LineKind::Quote, marks);
1600 self.open = false;
1601 }
1602 Span::List {
1603 ordered,
1604 start,
1605 items,
1606 } => {
1607 let depth = if kind.is_list() {
1608 (kind.depth() + 1).min(MAX_DEPTH)
1609 } else {
1610 0
1611 };
1612 let item_kind = if *ordered {
1613 LineKind::Numbered(depth)
1614 } else {
1615 LineKind::Bullet(depth)
1616 };
1617 for (position, item) in items.iter().enumerate() {
1618 let number = (position == 0).then_some(*start);
1619 self.start_line(&item_kind, number);
1620 self.walk(item, &item_kind, marks);
1621 }
1622 self.open = false;
1623 }
1624 Span::Table { rows, .. } => {
1625 for row in rows {
1626 self.start_line(&LineKind::Text, None);
1627 for (position, cell) in row.iter().enumerate() {
1628 if position > 0 {
1629 self.append(" | ", &LineKind::Text, &[]);
1630 }
1631 self.walk(cell, &LineKind::Text, marks);
1632 }
1633 }
1634 self.open = false;
1635 }
1636 Span::Image { .. } | Span::Quote(_) => {}
1637 }
1638 }
1639 }
1640
1641 fn finish(mut self) -> Vec<DraftLine> {
1642 let blank =
1643 |line: &DraftLine| line.kind == LineKind::Text && line.content.trim().is_empty();
1644 while self.lines.len() > 1 && self.lines.last().is_some_and(blank) {
1645 self.lines.pop();
1646 }
1647 while self.lines.len() > 1 && self.lines.first().is_some_and(blank) {
1648 self.lines.remove(0);
1649 }
1650 if self.lines.is_empty() {
1651 self.lines.push(DraftLine::text(""));
1652 }
1653 self.lines
1654 }
1655}
1656
1657#[cfg(test)]
1658mod tests {
1659 use super::*;
1660 use crate::html_to_spans;
1661
1662 fn typed(draft: &mut Draft, text: &str) {
1663 let mut typing: Option<TypingStyle> = None;
1664 for character in text.chars() {
1665 let cursor = draft.text().len();
1666 let mut next = draft.text().to_owned();
1667 next.push(character);
1668 let cursor = draft.apply_edit(&next, cursor + character.len_utf8(), typing.as_ref());
1669 typing = draft.convert_typed(cursor).map(|(_, style)| style);
1670 draft.take_edits();
1671 }
1672 }
1673
1674 fn typed_draft(text: &str) -> Draft {
1675 let mut draft = Draft::default();
1676 typed(&mut draft, text);
1677 draft
1678 }
1679
1680 fn mark(range: Range<usize>, kind: MarkKind) -> Mark {
1681 Mark { range, kind }
1682 }
1683
1684 #[test]
1685 fn typed_markdown_becomes_formatting() {
1686 let draft = typed_draft("a **bold** and *it* or _it_ ~~gone~~ `code`");
1687 assert_eq!(draft.text(), "a bold and it or it gone code");
1688 assert_eq!(
1689 draft.marks(),
1690 [
1691 mark(2..6, MarkKind::Bold),
1692 mark(11..13, MarkKind::Italic),
1693 mark(17..19, MarkKind::Italic),
1694 mark(20..24, MarkKind::Strike),
1695 mark(25..29, MarkKind::Code),
1696 ]
1697 );
1698 }
1699
1700 #[test]
1701 fn typed_link_keeps_the_label_and_carries_the_url() {
1702 let draft = typed_draft("see [docs](https://example.com)");
1703 assert_eq!(draft.text(), "see docs");
1704 assert_eq!(
1705 draft.marks(),
1706 [mark(4..8, MarkKind::Link("https://example.com".into()))]
1707 );
1708 }
1709
1710 #[test]
1711 fn snake_case_and_spaced_stars_stay_text() {
1712 assert_eq!(typed_draft("snake_case_name").text(), "snake_case_name");
1713 assert_eq!(typed_draft("2 * 3 * 4").text(), "2 * 3 * 4");
1714 assert!(typed_draft("a** b**").marks().is_empty());
1715 }
1716
1717 #[test]
1718 fn typing_at_the_end_of_bold_continues_it_but_not_after_a_link() {
1719 let mut draft = Draft::plain("b");
1720 draft.toggle(0..1, MarkKind::Bold);
1721 typed(&mut draft, "x");
1722 assert_eq!(draft.marks(), [mark(0..2, MarkKind::Bold)]);
1723 let converted = typed_draft("**b**x");
1724 assert_eq!(converted.marks(), [mark(0..1, MarkKind::Bold)]);
1725 let mut linked = typed_draft("[a](u)");
1726 typed(&mut linked, "b");
1727 assert_eq!(linked.marks(), [mark(0..1, MarkKind::Link("u".into()))]);
1728 }
1729
1730 #[test]
1731 fn typing_style_switches_bold_on_and_off_for_the_next_text() {
1732 let mut draft = Draft::plain("ab");
1733 let typing = TypingStyle {
1734 at: 2,
1735 add: vec![MarkKind::Bold],
1736 remove: Vec::new(),
1737 };
1738 draft.apply_edit("abc", 3, Some(&typing));
1739 assert_eq!(draft.marks(), [mark(2..3, MarkKind::Bold)]);
1740 let off = TypingStyle {
1741 at: 3,
1742 add: Vec::new(),
1743 remove: vec![MarkKind::Bold],
1744 };
1745 draft.apply_edit("abcd", 4, Some(&off));
1746 assert_eq!(draft.marks(), [mark(2..3, MarkKind::Bold)]);
1747 }
1748
1749 #[test]
1750 fn toggle_on_a_mixed_selection_formats_all_then_clears() {
1751 let mut draft = Draft::plain("hello world");
1752 draft.toggle(0..5, MarkKind::Bold);
1753 assert_eq!(draft.state(0..11, &MarkKind::Bold), FormatState::Mixed);
1754 draft.toggle(0..11, MarkKind::Bold);
1755 assert_eq!(draft.state(0..11, &MarkKind::Bold), FormatState::On);
1756 draft.toggle(0..11, MarkKind::Bold);
1757 assert_eq!(draft.state(0..11, &MarkKind::Bold), FormatState::Off);
1758 assert!(draft.marks().is_empty());
1759 }
1760
1761 #[test]
1762 fn deleting_inside_and_across_marks_shifts_and_clips() {
1763 let mut draft = Draft::plain("aa bold cc");
1764 draft.toggle(3..7, MarkKind::Bold);
1765 draft.apply_edit("aa bld cc", 4, None);
1766 assert_eq!(draft.marks(), [mark(3..6, MarkKind::Bold)]);
1767 draft.apply_edit("ald cc", 1, None);
1768 assert_eq!(draft.marks(), [mark(1..3, MarkKind::Bold)]);
1769 draft.apply_edit("XXald cc", 2, None);
1770 assert_eq!(draft.marks(), [mark(3..5, MarkKind::Bold)]);
1771 }
1772
1773 #[test]
1774 fn repeated_characters_are_attributed_to_the_cursor() {
1775 let mut draft = Draft::plain("aa");
1776 draft.toggle(0..1, MarkKind::Bold);
1777 draft.apply_edit("aaa", 2, None);
1778 assert_eq!(draft.marks(), [mark(0..2, MarkKind::Bold)]);
1779 }
1780
1781 #[test]
1782 fn list_shortcuts_turn_lines_into_items() {
1783 let draft = typed_draft("- one");
1784 assert_eq!(draft.text(), "• one");
1785 assert_eq!(draft.lines(), [LineKind::Bullet(0)]);
1786 let numbered = typed_draft("1. one");
1787 assert_eq!(numbered.text(), "1. one");
1788 assert_eq!(numbered.lines(), [LineKind::Numbered(0)]);
1789 let quote = typed_draft("> said");
1790 assert_eq!(quote.text(), format!("{QUOTE_MARKER}said"));
1791 assert_eq!(quote.lines(), [LineKind::Quote]);
1792 }
1793
1794 #[test]
1795 fn enter_continues_a_list_and_ends_it_on_an_empty_item() {
1796 let mut draft = typed_draft("1. one");
1797 let cursor = draft.break_line(draft.text().len(), false).unwrap();
1798 assert_eq!(draft.text(), "1. one\n2. ");
1799 assert_eq!(cursor, draft.text().len());
1800 typed(&mut draft, "two");
1801 let cursor = draft.break_line(draft.text().len(), false).unwrap();
1802 let cursor = draft.break_line(cursor, false).unwrap();
1803 assert_eq!(draft.text(), "1. one\n2. two\n");
1804 assert_eq!(cursor, draft.text().len());
1805 assert_eq!(draft.lines()[2], LineKind::Text);
1806 assert_eq!(Draft::plain("x").break_line(1, false), None);
1807 }
1808
1809 #[test]
1810 fn enter_in_the_middle_of_an_item_splits_it_and_renumbers() {
1811 let mut draft = Draft::from_markdown("1. ab\n2. c");
1812 draft.break_line(4, false).unwrap();
1813 assert_eq!(draft.text(), "1. a\n2. b\n3. c");
1814 let edits = draft.take_edits();
1815 assert_eq!(map_offset(&edits, 4), 8);
1816 }
1817
1818 #[test]
1819 fn tab_nests_and_shift_tab_lifts_list_items() {
1820 let mut draft = Draft::from_markdown("- a\n- b");
1821 assert!(draft.indent(6..6, false));
1822 assert_eq!(draft.lines(), [LineKind::Bullet(0), LineKind::Bullet(1)]);
1823 assert_eq!(draft.text(), format!("• a\n{INDENT}◦ b"));
1824 assert!(draft.indent(draft.text().len()..draft.text().len(), true));
1825 assert!(draft.indent(draft.text().len()..draft.text().len(), true));
1826 assert_eq!(draft.text(), "• a\nb");
1827 assert!(!Draft::plain("x").indent(0..0, false));
1828 }
1829
1830 #[test]
1831 fn nested_numbering_counts_per_level() {
1832 let draft = Draft::from_markdown("1. a\n 1. x\n 2. y\n2. b");
1833 assert_eq!(
1834 draft.text(),
1835 format!("1. a\n{INDENT}1. x\n{INDENT}2. y\n2. b")
1836 );
1837 }
1838
1839 #[test]
1840 fn backspace_at_an_item_start_drops_the_bullet() {
1841 let mut draft = Draft::from_markdown("- a");
1842 let cursor = draft.backspace_at_start(bullet_marker(0).len()).unwrap();
1843 assert_eq!((draft.text(), cursor), ("a", 0));
1844 assert_eq!(draft.lines(), [LineKind::Text]);
1845 }
1846
1847 #[test]
1848 fn typing_before_a_bullet_lands_after_it() {
1849 let mut draft = Draft::from_markdown("- a");
1850 let marker = bullet_marker(0);
1851 let cursor = draft.apply_edit(&format!("x{marker}a"), 1, None);
1852 assert_eq!(draft.text(), format!("{marker}xa"));
1853 assert_eq!(cursor, marker.len() + 1);
1854 assert_eq!(
1855 draft.take_edits(),
1856 [
1857 (0..1, String::new()),
1858 (marker.len() + 1..marker.len() + 1, "x".to_owned())
1859 ]
1860 );
1861 }
1862
1863 #[test]
1864 fn a_damaged_marker_turns_the_line_into_text() {
1865 let mut draft = Draft::from_markdown("- a");
1866 draft.apply_edit("•a", 1, None);
1867 assert_eq!(draft.lines(), [LineKind::Text]);
1868 }
1869
1870 #[test]
1871 fn fence_and_enter_open_a_code_block_that_enter_continues() {
1872 let mut draft = typed_draft("```rust");
1873 let cursor = draft.break_line(draft.text().len(), false).unwrap();
1874 assert_eq!((draft.text(), cursor), ("", 0));
1875 assert_eq!(draft.lines(), [LineKind::Code(Some("rust".into()))]);
1876 typed(&mut draft, "fn x() {}");
1877 let cursor = draft.break_line(draft.text().len(), false).unwrap();
1878 assert_eq!(draft.lines().len(), 2);
1879 assert_eq!(draft.break_line(cursor, false), Some(cursor));
1880 assert_eq!(draft.lines()[1], LineKind::Text);
1881 assert_eq!(
1882 draft.to_html(),
1883 "<pre class=\"language-rust\">fn x() {}</pre>"
1884 );
1885 }
1886
1887 #[test]
1888 fn markdown_inside_code_stays_literal() {
1889 let mut draft = typed_draft("```");
1890 let cursor = draft.break_line(3, false).unwrap();
1891 assert_eq!(cursor, 0);
1892 typed(&mut draft, "a **b**");
1893 assert_eq!(draft.text(), "a **b**");
1894 assert!(draft.marks().is_empty());
1895 }
1896
1897 #[test]
1898 fn html_nests_overlapping_marks_and_escapes() {
1899 let mut draft = Draft::plain("a<b & c");
1900 draft.toggle(0..4, MarkKind::Bold);
1901 draft.toggle(2..7, MarkKind::Italic);
1902 assert_eq!(draft.to_html(), "<b>a&lt;<i>b </i></b><i>&amp; c</i>");
1903 }
1904
1905 #[test]
1906 fn html_covers_every_format() {
1907 let draft = Draft::from_markdown(
1908 "**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```",
1909 );
1910 let mut underlined = draft.clone();
1911 underlined.toggle(0..1, MarkKind::Underline);
1912 assert_eq!(
1913 underlined.to_html(),
1914 "<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>\
1915 <blockquote>q1<br>q2</blockquote>\
1916 <ul><li>a<ul><li>b</li></ul></li></ul>\
1917 <ol><li>x</li><li>y</li></ol>\
1918 <pre class=\"language-py\">print(1)</pre>"
1919 );
1920 }
1921
1922 #[test]
1923 fn ordered_lists_keep_their_start() {
1924 let draft = Draft::from_markdown("3. c\n4. d");
1925 assert_eq!(draft.to_html(), "<ol start=\"3\"><li>c</li><li>d</li></ol>");
1926 }
1927
1928 #[test]
1929 fn spans_round_trip_through_html() {
1930 let source = Draft::from_markdown(
1931 "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",
1932 );
1933 let back = Draft::from_spans(&html_to_spans(&source.to_html()));
1934 assert_eq!(back.text(), source.text());
1935 assert_eq!(back.lines(), source.lines());
1936 assert_eq!(back.marks(), source.marks());
1937 }
1938
1939 #[test]
1940 fn mentions_from_html_come_back_as_at_text() {
1941 let draft = Draft::from_spans(&html_to_spans("hi <at id=\"0\">Ada</at> <b>now</b>"));
1942 assert_eq!(draft.text(), "hi @Ada now");
1943 assert_eq!(draft.marks(), [mark(8..11, MarkKind::Bold)]);
1944 }
1945
1946 #[test]
1947 fn pasted_markdown_is_detected() {
1948 assert!(has_markdown("see **this**"));
1949 assert!(has_markdown("- a\n- b"));
1950 assert!(has_markdown("```\nx\n```"));
1951 assert!(!has_markdown("plain text, 2*3=6 and snake_case"));
1952 }
1953
1954 #[test]
1955 fn slices_carry_formatting_into_another_draft() {
1956 let source = Draft::from_markdown("intro **bold**\n- one\n- two");
1957 let end = source.text().len();
1958 let fragment = source.slice(6..end);
1959 assert_eq!(fragment[0].kind, LineKind::Text);
1960 assert_eq!(fragment[1].kind, LineKind::Bullet(0));
1961 let mut target = Draft::plain("x ");
1962 let cursor = target.insert_lines(2..2, &fragment);
1963 assert_eq!(target.text(), "x bold\n• one\n• two");
1964 assert_eq!(cursor, target.text().len());
1965 assert_eq!(target.marks(), [mark(2..6, MarkKind::Bold)]);
1966 assert_eq!(
1967 target.lines()[1..],
1968 [LineKind::Bullet(0), LineKind::Bullet(0)]
1969 );
1970 }
1971
1972 #[test]
1973 fn journal_merges_edits_into_ranges_of_the_old_text() {
1974 let mut draft = Draft::plain("a **b** c");
1975 draft.splice(5..7, "", &[]);
1976 draft.splice(2..4, "", &[]);
1977 draft.splice(0..0, "X", &[]);
1978 let edits = draft.take_edits();
1979 assert_eq!(
1980 edits,
1981 [
1982 (0..0, "X".to_owned()),
1983 (2..4, String::new()),
1984 (5..7, String::new())
1985 ]
1986 );
1987 assert_eq!(
1988 reverse_edits(&edits, "a **b** c")[1],
1989 (3..3, "**".to_owned())
1990 );
1991 let mut touching = Draft::plain("abc");
1992 touching.splice(1..2, "XY", &[]);
1993 touching.splice(3..3, "Z", &[]);
1994 assert_eq!(touching.take_edits(), [(1..2, "XYZ".to_owned())]);
1995 }
1996
1997 #[test]
1998 fn trimming_drops_blank_lines_and_outer_spaces() {
1999 let mut draft = Draft::plain("\n hi **x** \n\n");
2000 draft.toggle(6..11, MarkKind::Bold);
2001 let trimmed = draft.trimmed();
2002 assert_eq!(trimmed.text(), "hi **x**");
2003 assert_eq!(trimmed.marks(), [mark(3..8, MarkKind::Bold)]);
2004 }
2005
2006 #[test]
2007 fn toolbar_line_toggles_apply_to_every_selected_line() {
2008 let mut draft = Draft::plain("a\nb");
2009 draft.toggle_lines(0..3, LineKind::Numbered(0));
2010 assert_eq!(draft.text(), "1. a\n2. b");
2011 assert_eq!(
2012 draft.line_state(0..4, &LineKind::Numbered(0)),
2013 FormatState::On
2014 );
2015 draft.toggle_lines(0..9, LineKind::Bullet(0));
2016 assert_eq!(draft.text(), "• a\n• b");
2017 let end = draft.text().len();
2018 draft.toggle_lines(0..end, LineKind::Bullet(0));
2019 assert_eq!(draft.text(), "a\nb");
2020 }
2021
2022 #[test]
2023 fn links_are_set_replaced_and_removed() {
2024 let mut draft = Draft::plain("go here");
2025 draft.set_link(3..7, "https://a.test");
2026 assert_eq!(draft.link_in(4..4), Some("https://a.test".into()));
2027 draft.set_link(3..7, "");
2028 assert!(draft.marks().is_empty());
2029 let end = draft.insert_link(7, " https://b.test", "https://b.test");
2030 assert_eq!(end, draft.text().len());
2031 }
2032}
crates/core/src/lib.rs +5 −0
@@ -3,6 +3,7 @@ mod avatars;
3 3 mod card;
4 4 mod channel_sync;
5 5 mod download;
6 mod draft;
6 7 mod engine;
7 8 mod error;
8 9 mod events;
@@ -24,6 +25,10 @@ mod stored;
24 25
25 26 pub use avatars::Avatar;
26 27 pub use card::card_content_text;
28 pub use draft::{
29 Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, TypingStyle,
30 has_markdown, map_offset, reverse_edits,
31 };
27 32 pub use engine::{Delta, Me, SidebarSummary, SyncConfig, SyncEngine};
28 33 pub use error::{Error, Result};
29 34 pub use events::CoreEvent;
@@ -3,6 +3,7 @@ mod avatars;
3mod card;
3mod card;
4mod channel_sync;
4mod channel_sync;
5mod download;
5mod download;
6mod draft;
6mod engine;
7mod engine;
7mod error;
8mod error;
8mod events;
9mod events;
@@ -24,6 +25,10 @@ mod stored;
24
25
25pub use avatars::Avatar;
26pub use avatars::Avatar;
26pub use card::card_content_text;
27pub use card::card_content_text;
28pub use draft::{
29 Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, TypingStyle,
30 has_markdown, map_offset, reverse_edits,
31};
27pub use engine::{Delta, Me, SidebarSummary, SyncConfig, SyncEngine};
32pub use engine::{Delta, Me, SidebarSummary, SyncConfig, SyncEngine};
28pub use error::{Error, Result};
33pub use error::{Error, Result};
29pub use events::CoreEvent;
34pub use events::CoreEvent;
crates/core/src/mentions.rs +10 −0
@@ -141,6 +141,16 @@ mod tests {
141 141 assert_eq!(mentions[0].text, "Ada & Co");
142 142 }
143 143
144 #[test]
145 fn mentions_inside_formatted_draft_html_become_at_tags() {
146 let (html, mentions) = apply_mentions(
147 &crate::Draft::from_markdown("**hi @Ada** and `@Bo`").to_html(),
148 &[MentionInput::user("u1", "Ada")],
149 );
150 assert_eq!(html, "<b>hi <at id=\"0\">Ada</at></b> and <code>@Bo</code>");
151 assert_eq!(mentions.len(), 1);
152 }
153
144 154 #[test]
145 155 fn chats_only_take_user_mentions() {
146 156 assert!(ensure_allowed_in_chat(&[MentionInput::user("u", "A")]).is_ok());
@@ -141,6 +141,16 @@ mod tests {
141 assert_eq!(mentions[0].text, "Ada & Co");
141 assert_eq!(mentions[0].text, "Ada & Co");
142 }
142 }
143
143
144 #[test]
145 fn mentions_inside_formatted_draft_html_become_at_tags() {
146 let (html, mentions) = apply_mentions(
147 &crate::Draft::from_markdown("**hi @Ada** and `@Bo`").to_html(),
148 &[MentionInput::user("u1", "Ada")],
149 );
150 assert_eq!(html, "<b>hi <at id=\"0\">Ada</at></b> and <code>@Bo</code>");
151 assert_eq!(mentions.len(), 1);
152 }
153
144 #[test]
154 #[test]
145 fn chats_only_take_user_mentions() {
155 fn chats_only_take_user_mentions() {
146 assert!(ensure_allowed_in_chat(&[MentionInput::user("u", "A")]).is_ok());
156 assert!(ensure_allowed_in_chat(&[MentionInput::user("u", "A")]).is_ok());