BlueGit

ict rusty-teams

Files

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

draft.rs

draft.rs 126.9 KiB Download Raw
1use std::ops::Range;
2use std::sync::LazyLock;
3
4use regex::Regex;
5use serde::{Deserialize, Serialize};
6
7use crate::markdown::escape_html;
8use crate::spans::{FontSize, Span};
9use crate::table::{TABLE_MARK, Table, markdown_table};
10
11pub const MAX_DEPTH: u8 = 2;
12pub const MAX_HEADING: u8 = 3;
13pub const OBJECT_MARK: char = '\u{FFFC}';
14pub const RULE_MARK: char = '\u{FFFA}';
15pub const MAX_INDENT: u8 = 8;
16pub const INDENT_PIXELS: u32 = 40;
17pub const RULE_HTML: &str = "<hr>";
18const BULLETS: [&str; 3] = ["•", "◦", "▪"];
19const PASTED_BULLETS: [&str; 6] = ["- ", "* ", "+ ", "• ", "◦ ", "▪ "];
20const LINK_SCHEMES: [&str; 3] = ["http://", "https://", "mailto:"];
21const AUTOLINK_PREFIXES: [&str; 4] = ["http://", "https://", "www.", "mailto:"];
22const AUTOLINK_TRAILING: &str = ".,;:!?'\"";
23const FENCE: &str = "```";
24const PLAIN_LANGUAGE: &str = "plaintext";
25const MARKDOWN_INDENT: usize = 2;
26
27static TYPED_LINK: LazyLock<Regex> =
28 LazyLock::new(|| Regex::new(r"\[([^\]\n]+)\]\(([^)\s]+)\)$").unwrap());
29static LINK_AT: LazyLock<Regex> =
30 LazyLock::new(|| Regex::new(r"^\[([^\]\n]+)\]\(([^)\s]+)\)").unwrap());
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
33pub enum SizeStep {
34 Small,
35 Large,
36}
37
38impl SizeStep {
39 fn css(self) -> &'static str {
40 match self {
41 SizeStep::Small => "xx-small",
42 SizeStep::Large => "x-large",
43 }
44 }
45}
46
47#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
48pub enum MarkKind {
49 Link(String),
50 Bold,
51 Italic,
52 Underline,
53 Strike,
54 Superscript,
55 Subscript,
56 Size(SizeStep),
57 Color(u32),
58 Highlight(u32),
59 Code,
60}
61
62impl MarkKind {
63 pub fn same_format(&self, other: &MarkKind) -> bool {
64 std::mem::discriminant(self) == std::mem::discriminant(other)
65 }
66
67 fn covers(&self, other: &MarkKind) -> bool {
68 match (self, other) {
69 (MarkKind::Size(left), MarkKind::Size(right)) => left == right,
70 (MarkKind::Color(left), MarkKind::Color(right)) => left == right,
71 (MarkKind::Highlight(left), MarkKind::Highlight(right)) => left == right,
72 _ => self.same_format(other),
73 }
74 }
75
76 fn opposite_script(&self) -> Option<MarkKind> {
77 match self {
78 MarkKind::Superscript => Some(MarkKind::Subscript),
79 MarkKind::Subscript => Some(MarkKind::Superscript),
80 _ => None,
81 }
82 }
83
84 fn continues_at_end(&self) -> bool {
85 matches!(
86 self,
87 MarkKind::Bold
88 | MarkKind::Italic
89 | MarkKind::Underline
90 | MarkKind::Strike
91 | MarkKind::Superscript
92 | MarkKind::Subscript
93 | MarkKind::Size(_)
94 | MarkKind::Color(_)
95 | MarkKind::Highlight(_)
96 )
97 }
98
99 fn open_tag(&self) -> String {
100 match self {
101 MarkKind::Link(url) => format!("<a href=\"{}\">", escape_html(url)),
102 MarkKind::Bold => "<b>".to_owned(),
103 MarkKind::Italic => "<i>".to_owned(),
104 MarkKind::Underline => "<u>".to_owned(),
105 MarkKind::Strike => "<s>".to_owned(),
106 MarkKind::Superscript => "<sup>".to_owned(),
107 MarkKind::Subscript => "<sub>".to_owned(),
108 MarkKind::Size(step) => format!("<span style=\"font-size:{};\">", step.css()),
109 MarkKind::Color(color) => format!("<span style=\"color:{};\">", hex_color(*color)),
110 MarkKind::Highlight(color) => {
111 format!("<span style=\"background-color:{};\">", hex_color(*color))
112 }
113 MarkKind::Code => "<code>".to_owned(),
114 }
115 }
116
117 fn close_tag(&self) -> &'static str {
118 match self {
119 MarkKind::Link(_) => "</a>",
120 MarkKind::Bold => "</b>",
121 MarkKind::Italic => "</i>",
122 MarkKind::Underline => "</u>",
123 MarkKind::Strike => "</s>",
124 MarkKind::Superscript => "</sup>",
125 MarkKind::Subscript => "</sub>",
126 MarkKind::Size(_) | MarkKind::Color(_) | MarkKind::Highlight(_) => "</span>",
127 MarkKind::Code => "</code>",
128 }
129 }
130}
131
132#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
133pub struct Mark {
134 pub range: Range<usize>,
135 pub kind: MarkKind,
136}
137
138#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
139pub enum LineKind {
140 Text,
141 Indent(u8),
142 Bullet(u8),
143 Numbered(u8),
144 Quote,
145 Code(Option<String>),
146 Heading(u8),
147 Table(Table),
148 Rule,
149}
150
151impl LineKind {
152 pub fn is_list(&self) -> bool {
153 matches!(self, LineKind::Bullet(_) | LineKind::Numbered(_))
154 }
155
156 pub fn is_table(&self) -> bool {
157 matches!(self, LineKind::Table(_))
158 }
159
160 /// A line that holds one object mark alone: a table or a horizontal rule.
161 pub fn object_mark(&self) -> Option<char> {
162 match self {
163 LineKind::Table(_) => Some(TABLE_MARK),
164 LineKind::Rule => Some(RULE_MARK),
165 _ => None,
166 }
167 }
168
169 pub fn depth(&self) -> u8 {
170 match self {
171 LineKind::Bullet(depth) | LineKind::Numbered(depth) => *depth,
172 _ => 0,
173 }
174 }
175
176 pub fn same_format(&self, other: &LineKind) -> bool {
177 std::mem::discriminant(self) == std::mem::discriminant(other)
178 }
179
180 fn with_depth(&self, depth: u8) -> LineKind {
181 match self {
182 LineKind::Bullet(_) => LineKind::Bullet(depth),
183 LineKind::Numbered(_) => LineKind::Numbered(depth),
184 other => other.clone(),
185 }
186 }
187}
188
189#[derive(Debug, Clone, Copy, PartialEq, Eq)]
190pub enum FormatState {
191 Off,
192 Mixed,
193 On,
194}
195
196/// Formats switched on or off for text typed at `at` before any is typed.
197#[derive(Debug, Clone, Default, PartialEq, Eq)]
198pub struct TypingStyle {
199 pub at: usize,
200 pub add: Vec<MarkKind>,
201 pub remove: Vec<MarkKind>,
202}
203
204impl TypingStyle {
205 pub fn apply(&self, mut kinds: Vec<MarkKind>) -> Vec<MarkKind> {
206 kinds.retain(|kind| !self.remove.iter().any(|removed| removed.same_format(kind)));
207 for added in &self.add {
208 if !kinds.iter().any(|kind| kind.same_format(added)) {
209 kinds.push(added.clone());
210 }
211 }
212 kinds
213 }
214
215 pub fn toggle(&mut self, kind: MarkKind, active: &[MarkKind]) {
216 let is_active = self
217 .apply(active.to_vec())
218 .iter()
219 .any(|existing| existing.same_format(&kind));
220 self.add.retain(|added| !added.same_format(&kind));
221 self.remove.retain(|removed| !removed.same_format(&kind));
222 let inherited = active.iter().any(|existing| existing.same_format(&kind));
223 match (is_active, inherited) {
224 (true, true) => self.remove.push(kind.clone()),
225 (false, false) => self.add.push(kind.clone()),
226 _ => {}
227 }
228 if let Some(opposite) = kind.opposite_script()
229 && self.add.contains(&kind)
230 {
231 self.add.retain(|added| !added.same_format(&opposite));
232 self.remove
233 .retain(|removed| !removed.same_format(&opposite));
234 if active
235 .iter()
236 .any(|existing| existing.same_format(&opposite))
237 {
238 self.remove.push(opposite);
239 }
240 }
241 }
242
243 /// `None` is the normal size.
244 pub fn set_size(&mut self, size: Option<SizeStep>, active: &[MarkKind]) {
245 self.set_exclusive(
246 MarkKind::Size(SizeStep::Small),
247 size.map(MarkKind::Size),
248 active,
249 );
250 }
251
252 /// `None` is Automatic.
253 pub fn set_color(&mut self, color: Option<u32>, active: &[MarkKind]) {
254 self.set_exclusive(MarkKind::Color(0), color.map(MarkKind::Color), active);
255 }
256
257 /// `None` is No highlight.
258 pub fn set_highlight(&mut self, color: Option<u32>, active: &[MarkKind]) {
259 self.set_exclusive(
260 MarkKind::Highlight(0),
261 color.map(MarkKind::Highlight),
262 active,
263 );
264 }
265
266 /// Text typed next drops every format but a link.
267 pub fn clear(&mut self, active: &[MarkKind]) {
268 self.add.clear();
269 self.remove = active
270 .iter()
271 .filter(|kind| !matches!(kind, MarkKind::Link(_)))
272 .cloned()
273 .collect();
274 }
275
276 fn set_exclusive(&mut self, marker: MarkKind, value: Option<MarkKind>, active: &[MarkKind]) {
277 self.add.retain(|added| !added.same_format(&marker));
278 self.remove.retain(|removed| !removed.same_format(&marker));
279 if active.iter().any(|existing| existing.same_format(&marker)) {
280 self.remove.push(marker);
281 }
282 self.add.extend(value);
283 }
284
285 pub fn is_empty(&self) -> bool {
286 self.add.is_empty() && self.remove.is_empty()
287 }
288}
289
290/// One line without its marker: what the clipboard and `from_lines` carry.
291#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
292pub struct DraftLine {
293 pub kind: LineKind,
294 pub number: Option<u32>,
295 pub content: String,
296 pub marks: Vec<Mark>,
297}
298
299impl DraftLine {
300 fn text(content: &str) -> DraftLine {
301 DraftLine {
302 kind: LineKind::Text,
303 number: None,
304 content: content.to_owned(),
305 marks: Vec::new(),
306 }
307 }
308
309 fn trim_start(&mut self) {
310 let cut = self.content.len() - self.content.trim_start().len();
311 self.content.drain(..cut);
312 for mark in &mut self.marks {
313 mark.range = mark.range.start.saturating_sub(cut)..mark.range.end.saturating_sub(cut);
314 }
315 self.marks.retain(|mark| !mark.range.is_empty());
316 }
317
318 fn trim_end(&mut self) {
319 let length = self.content.trim_end().len();
320 self.content.truncate(length);
321 for mark in &mut self.marks {
322 mark.range = mark.range.start.min(length)..mark.range.end.min(length);
323 }
324 self.marks.retain(|mark| !mark.range.is_empty());
325 }
326}
327
328pub type Edit = (Range<usize>, String);
329
330/// Edits since the last `take_edits`, as disjoint ranges of the text at that point.
331#[derive(Debug, Clone, Default)]
332struct Journal(Vec<Edit>);
333
334impl PartialEq for Journal {
335 fn eq(&self, _: &Journal) -> bool {
336 true
337 }
338}
339
340impl Eq for Journal {}
341
342impl Journal {
343 fn record(&mut self, range: Range<usize>, inserted: usize, text: &str) {
344 if range.is_empty() && inserted == 0 {
345 return;
346 }
347 let mut delta = 0isize;
348 let mut delta_before = 0isize;
349 let mut position = self.0.len();
350 let mut touching: Vec<(usize, usize, usize)> = Vec::new();
351 for (index, (original, replacement)) in self.0.iter().enumerate() {
352 let current_start = (original.start as isize + delta) as usize;
353 let current_end = current_start + replacement.len();
354 if current_end < range.start {
355 delta += replacement.len() as isize - original.len() as isize;
356 delta_before = delta;
357 continue;
358 }
359 if current_start > range.end {
360 position = position.min(index);
361 break;
362 }
363 position = position.min(index);
364 touching.push((index, current_start, current_end));
365 delta += replacement.len() as isize - original.len() as isize;
366 }
367 let original_start = match touching.first() {
368 Some(&(index, current_start, _)) if current_start <= range.start => {
369 self.0[index].0.start
370 }
371 _ => (range.start as isize - delta_before) as usize,
372 };
373 let original_end = match touching.last() {
374 Some(&(index, _, current_end)) if current_end >= range.end => self.0[index].0.end,
375 _ => (range.end as isize - delta) as usize,
376 };
377 let merged_start = touching
378 .first()
379 .map_or(range.start, |&(_, current_start, _)| {
380 current_start.min(range.start)
381 });
382 let merged_end = touching
383 .last()
384 .map_or(range.end, |&(_, _, current_end)| current_end.max(range.end));
385 let merged_end_after = merged_end + inserted - range.len();
386 let replacement = text[merged_start..merged_end_after].to_owned();
387 if let (Some(&(first, ..)), Some(&(last, ..))) = (touching.first(), touching.last()) {
388 self.0.drain(first..=last);
389 }
390 self.0
391 .insert(position, (original_start..original_end, replacement));
392 }
393}
394
395/// Where `offset` of the text before `edits` ends up; an insertion at it pushes it along.
396pub fn map_offset(edits: &[Edit], offset: usize) -> usize {
397 let mut delta = 0isize;
398 for (original, replacement) in edits {
399 if offset >= original.end {
400 delta += replacement.len() as isize - original.len() as isize;
401 } else if offset > original.start {
402 return (original.start as isize + delta) as usize + replacement.len();
403 } else {
404 break;
405 }
406 }
407 (offset as isize + delta) as usize
408}
409
410/// The edits that turn the text after `edits` back into `before`.
411pub fn reverse_edits(edits: &[Edit], before: &str) -> Vec<Edit> {
412 let mut delta = 0isize;
413 edits
414 .iter()
415 .map(|(original, replacement)| {
416 let start = (original.start as isize + delta) as usize;
417 delta += replacement.len() as isize - original.len() as isize;
418 (
419 start..start + replacement.len(),
420 before[original.clone()].to_owned(),
421 )
422 })
423 .collect()
424}
425
426/// Composer text plus formatting. List and quote lines carry their marker in `text`.
427#[derive(Debug, Clone, PartialEq, Eq)]
428pub struct Draft {
429 text: String,
430 marks: Vec<Mark>,
431 lines: Vec<LineKind>,
432 journal: Journal,
433}
434
435impl Default for Draft {
436 fn default() -> Self {
437 Draft::plain("")
438 }
439}
440
441impl Draft {
442 pub fn plain(text: &str) -> Draft {
443 Draft {
444 text: text.to_owned(),
445 marks: Vec::new(),
446 lines: vec![LineKind::Text; text.matches('\n').count() + 1],
447 journal: Journal::default(),
448 }
449 }
450
451 pub fn from_lines(lines: &[DraftLine]) -> Draft {
452 let mut draft = Draft::plain("");
453 draft.insert_lines(0..0, lines);
454 draft.journal = Journal::default();
455 draft
456 }
457
458 pub fn to_lines(&self) -> Vec<DraftLine> {
459 self.slice(0..self.text.len())
460 }
461
462 pub fn from_markdown(text: &str) -> Draft {
463 Draft::from_lines(&markdown_lines(text))
464 }
465
466 pub fn from_spans(spans: &[Span]) -> Draft {
467 let mut builder = SpanLines::default();
468 builder.walk(spans, &LineKind::Text, &[]);
469 Draft::from_lines(&builder.finish())
470 }
471
472 pub fn text(&self) -> &str {
473 &self.text
474 }
475
476 pub fn marks(&self) -> &[Mark] {
477 &self.marks
478 }
479
480 pub fn lines(&self) -> &[LineKind] {
481 &self.lines
482 }
483
484 pub fn take_edits(&mut self) -> Vec<Edit> {
485 std::mem::take(&mut self.journal.0)
486 }
487
488 pub fn is_blank(&self) -> bool {
489 self.plain_text().trim().is_empty()
490 }
491
492 /// The text without list and quote markers and object marks.
493 pub fn plain_text(&self) -> String {
494 self.slice(0..self.text.len())
495 .into_iter()
496 .map(|line| match &line.kind {
497 LineKind::Table(table) => table.plain_text(),
498 LineKind::Rule => String::new(),
499 _ => line.content,
500 })
501 .collect::<Vec<_>>()
502 .join("\n")
503 .replace(&format!(" {OBJECT_MARK} "), " ")
504 .replace(OBJECT_MARK, "")
505 }
506
507 pub fn line_ranges(&self) -> Vec<Range<usize>> {
508 let mut ranges = Vec::with_capacity(self.lines.len());
509 let mut start = 0;
510 for (index, _) in self.text.match_indices('\n') {
511 ranges.push(start..index);
512 start = index + 1;
513 }
514 ranges.push(start..self.text.len());
515 ranges
516 }
517
518 pub fn line_at(&self, offset: usize) -> usize {
519 let offset = offset.min(self.text.len());
520 self.text.as_bytes()[..offset]
521 .iter()
522 .filter(|byte| **byte == b'\n')
523 .count()
524 }
525
526 pub fn marker_range(&self, index: usize) -> Range<usize> {
527 let line = self.line_ranges()[index].clone();
528 let length = marker_len(&self.lines[index], &self.text[line.clone()]);
529 line.start..line.start + length
530 }
531
532 pub fn content_range(&self, index: usize) -> Range<usize> {
533 let line = self.line_ranges()[index].clone();
534 self.marker_range(index).end..line.end
535 }
536
537 /// Inside a code block line, or strictly inside inline code.
538 pub fn in_code(&self, offset: usize) -> bool {
539 matches!(self.lines[self.line_at(offset)], LineKind::Code(_))
540 || self.marks.iter().any(|mark| {
541 mark.kind == MarkKind::Code && mark.range.start < offset && offset < mark.range.end
542 })
543 }
544
545 /// Formats that text typed at `offset` takes on.
546 pub fn style_at(&self, offset: usize) -> Vec<MarkKind> {
547 self.style_for_insertion(offset, offset)
548 }
549
550 pub fn state(&self, range: Range<usize>, kind: &MarkKind) -> FormatState {
551 let parts = self.content_parts(range);
552 let total: usize = parts.iter().map(|part| part.len()).sum();
553 if total == 0 {
554 return FormatState::Off;
555 }
556 let covered: usize = parts
557 .iter()
558 .map(|part| {
559 let mut ranges: Vec<Range<usize>> = self
560 .marks
561 .iter()
562 .filter(|mark| mark.kind.covers(kind))
563 .map(|mark| mark.range.start.max(part.start)..mark.range.end.min(part.end))
564 .filter(|range| !range.is_empty())
565 .collect();
566 ranges.sort_by_key(|range| range.start);
567 let mut end = part.start;
568 let mut sum = 0;
569 for range in ranges {
570 let start = range.start.max(end);
571 if range.end > start {
572 sum += range.end - start;
573 end = range.end;
574 }
575 }
576 sum
577 })
578 .sum();
579 match covered {
580 0 => FormatState::Off,
581 covered if covered >= total => FormatState::On,
582 _ => FormatState::Mixed,
583 }
584 }
585
586 /// A line the selection only touches at its start does not count.
587 fn selected_lines(&self, range: &Range<usize>) -> std::ops::RangeInclusive<usize> {
588 let first = self.line_at(range.start);
589 let mut last = self.line_at(range.end);
590 if last > first && self.line_ranges()[last].start == range.end {
591 last -= 1;
592 }
593 first..=last
594 }
595
596 pub fn line_state(&self, range: Range<usize>, kind: &LineKind) -> FormatState {
597 let lines = self.selected_lines(&range);
598 let count = lines.clone().count();
599 let matching = lines
600 .filter(|index| self.lines[*index].same_format(kind))
601 .count();
602 match matching {
603 0 => FormatState::Off,
604 matching if matching == count => FormatState::On,
605 _ => FormatState::Mixed,
606 }
607 }
608
609 pub fn link_in(&self, range: Range<usize>) -> Option<String> {
610 self.marks.iter().find_map(|mark| match &mark.kind {
611 MarkKind::Link(url)
612 if mark.range.start < range.end.max(range.start + 1)
613 && range.start < mark.range.end =>
614 {
615 Some(url.clone())
616 }
617 _ => None,
618 })
619 }
620
621 /// Mixed or off: the whole range gets `kind`. On: it loses it.
622 pub fn toggle(&mut self, range: Range<usize>, kind: MarkKind) {
623 self.journal = Journal::default();
624 if self.state(range.clone(), &kind) == FormatState::On {
625 self.remove_marks(range, &kind);
626 } else {
627 if let Some(opposite) = kind.opposite_script() {
628 self.remove_marks(range.clone(), &opposite);
629 }
630 for part in self.content_parts(range) {
631 self.add_mark(part, kind.clone());
632 }
633 }
634 }
635
636 /// `None` is the normal size: any size mark on `range` is removed.
637 pub fn set_size(&mut self, range: Range<usize>, size: Option<SizeStep>) {
638 self.set_exclusive(
639 range,
640 &MarkKind::Size(SizeStep::Small),
641 size.map(MarkKind::Size),
642 );
643 }
644
645 /// `None` is Automatic: the font colour on `range` is removed.
646 pub fn set_color(&mut self, range: Range<usize>, color: Option<u32>) {
647 self.set_exclusive(range, &MarkKind::Color(0), color.map(MarkKind::Color));
648 }
649
650 /// `None` is No highlight.
651 pub fn set_highlight(&mut self, range: Range<usize>, color: Option<u32>) {
652 self.set_exclusive(
653 range,
654 &MarkKind::Highlight(0),
655 color.map(MarkKind::Highlight),
656 );
657 }
658
659 /// The colour of `marker`'s kind that covers all of `range`.
660 pub fn color_in(&self, range: Range<usize>, marker: &MarkKind) -> Option<u32> {
661 self.marks
662 .iter()
663 .filter(|mark| mark.kind.same_format(marker))
664 .find(|mark| self.state(range.clone(), &mark.kind) == FormatState::On)
665 .and_then(|mark| match mark.kind {
666 MarkKind::Color(color) | MarkKind::Highlight(color) => Some(color),
667 _ => None,
668 })
669 }
670
671 /// Teams' Clear all formatting: every inline format but links, and the block indent.
672 pub fn clear_formatting(&mut self, range: Range<usize>) {
673 self.journal = Journal::default();
674 let kinds: Vec<MarkKind> = self
675 .marks
676 .iter()
677 .filter(|mark| !matches!(mark.kind, MarkKind::Link(_)) && overlaps(&mark.range, &range))
678 .map(|mark| mark.kind.clone())
679 .collect();
680 for kind in kinds {
681 self.remove_marks(range.clone(), &kind);
682 }
683 for index in self.selected_lines(&range) {
684 if matches!(self.lines[index], LineKind::Indent(_)) {
685 self.lines[index] = LineKind::Text;
686 }
687 }
688 }
689
690 fn set_exclusive(&mut self, range: Range<usize>, marker: &MarkKind, value: Option<MarkKind>) {
691 self.journal = Journal::default();
692 self.remove_marks(range.clone(), marker);
693 if let Some(kind) = value {
694 for part in self.content_parts(range) {
695 self.add_mark(part, kind.clone());
696 }
697 }
698 }
699
700 pub fn size_in(&self, range: Range<usize>) -> Option<SizeStep> {
701 [SizeStep::Small, SizeStep::Large]
702 .into_iter()
703 .find(|step| self.state(range.clone(), &MarkKind::Size(*step)) == FormatState::On)
704 }
705
706 /// An empty `url` removes the link; one `link_url` refuses changes nothing.
707 pub fn set_link(&mut self, range: Range<usize>, url: &str) {
708 self.journal = Journal::default();
709 let url = url.trim();
710 if !url.is_empty() && link_url(url).is_none() {
711 return;
712 }
713 let link = MarkKind::Link(url.to_owned());
714 self.remove_marks(range.clone(), &link);
715 if !url.is_empty() {
716 for part in self.content_parts(range) {
717 self.add_mark(part, link.clone());
718 }
719 }
720 }
721
722 /// Returns the offset after the inserted link text; plain text when `link_url` refuses `url`.
723 pub fn insert_link(&mut self, offset: usize, text: &str, url: &str) -> usize {
724 self.journal = Journal::default();
725 self.splice(offset..offset, text, &[]);
726 self.add_mark(offset..offset + text.len(), MarkKind::Link(url.to_owned()));
727 offset + text.len()
728 }
729
730 /// Replaces `range`, the new text taking on the format of the text it replaces.
731 pub fn replace(&mut self, range: Range<usize>, text: &str) {
732 self.journal = Journal::default();
733 let kinds = self.style_for_insertion(range.start, range.end);
734 self.splice(range, text, &kinds);
735 }
736
737 /// Takes the composer text after an edit the user made. Returns the cursor, moved when a
738 /// marker had to be repaired or the typed text moved out of one.
739 pub fn apply_edit(
740 &mut self,
741 new_text: &str,
742 cursor: usize,
743 typing: Option<&TypingStyle>,
744 ) -> usize {
745 self.journal = Journal::default();
746 if new_text == self.text {
747 return cursor;
748 }
749 let (start, old_end, new_end) = edit_span(&self.text, new_text, cursor);
750 let replacement = new_text[start..new_end].to_owned();
751 let mut kinds = self.style_for_insertion(start, old_end);
752 if let Some(typing) = typing.filter(|typing| typing.at == start) {
753 kinds = typing.apply(kinds);
754 }
755 let marker = self.marker_range(self.line_at(start));
756 let auto_urls = self.auto_link_urls(&(start..old_end));
757 self.splice(start..old_end, &replacement, &kinds);
758 self.retarget_links(&auto_urls, &(start..start + replacement.len()));
759 self.journal = Journal::default();
760 let mut cursor = cursor.min(self.text.len());
761 let typed_into_marker = old_end == start
762 && !replacement.contains('\n')
763 && !marker.is_empty()
764 && (marker.start..marker.end).contains(&start);
765 if typed_into_marker {
766 self.splice(start..start + replacement.len(), "", &[]);
767 self.splice(marker.end..marker.end, &replacement, &kinds);
768 cursor = marker.end + replacement.len();
769 }
770 self.repair(cursor)
771 }
772
773 /// Markdown typed just before `cursor` turns into formatting. Returns the new cursor and
774 /// the style for what is typed next, so text after `**bold**` is not bold.
775 pub fn convert_typed(&mut self, cursor: usize) -> Option<(usize, TypingStyle)> {
776 self.journal = Journal::default();
777 let index = self.line_at(cursor);
778 if matches!(self.lines[index], LineKind::Code(_)) {
779 return None;
780 }
781 let content = self.content_range(index);
782 if cursor < content.start || cursor > content.end {
783 return None;
784 }
785 let before = &self.text[content.start..cursor];
786 if self.lines[index] == LineKind::Text
787 && let Some((kind, number)) = line_shortcut(before)
788 {
789 self.splice(content.start..cursor, &marker_text(&kind, number), &[]);
790 self.lines[index] = kind;
791 let after_marker = self.content_range(index).start;
792 let cursor = self.repair(after_marker);
793 return Some((
794 cursor,
795 TypingStyle {
796 at: cursor,
797 ..TypingStyle::default()
798 },
799 ));
800 }
801 let (open, close, kind) = typed_inline(before)?;
802 let open = content.start + open.start..content.start + open.end;
803 let close = content.start + close.start..content.start + close.end;
804 let inside_code = self.marks.iter().any(|mark| {
805 mark.kind == MarkKind::Code
806 && (overlaps(&mark.range, &open) || overlaps(&mark.range, &close))
807 });
808 if inside_code {
809 return None;
810 }
811 self.splice(close.clone(), "", &[]);
812 self.splice(open.clone(), "", &[]);
813 let inner = open.start..close.start - open.len();
814 self.add_mark(inner, kind.clone());
815 let cursor = cursor - open.len() - close.len();
816 Some((
817 cursor,
818 TypingStyle {
819 at: cursor,
820 add: Vec::new(),
821 remove: vec![kind],
822 },
823 ))
824 }
825
826 /// A URL typed just before the space or newline at `cursor - 1` becomes a link.
827 pub fn autolink_typed(&mut self, cursor: usize) -> bool {
828 self.journal = Journal::default();
829 let Some(end) = cursor.checked_sub(1) else {
830 return false;
831 };
832 if !matches!(self.text.get(end..cursor), Some(" " | "\n")) {
833 return false;
834 }
835 self.link_word_ending_at(end)
836 }
837
838 /// Links the URL in the word that ends at `end`. Leaves the journal alone.
839 pub fn link_word_ending_at(&mut self, end: usize) -> bool {
840 let index = self.line_at(end);
841 if matches!(self.lines[index], LineKind::Code(_)) {
842 return false;
843 }
844 let content_start = self.content_range(index).start;
845 let Some(before) = self.text.get(content_start..end) else {
846 return false;
847 };
848 let word_start = before.rfind(char::is_whitespace).map_or(0, |at| {
849 at + before[at..].chars().next().map_or(1, char::len_utf8)
850 });
851 let word = &before[word_start..];
852 let Some(found) = word.char_indices().find_map(|(offset, _)| {
853 let previous = word[..offset].chars().next_back();
854 let length = bare_url_at(&word[offset..], previous)?;
855 Some(offset..offset + length)
856 }) else {
857 return false;
858 };
859 let range =
860 content_start + word_start + found.start..content_start + word_start + found.end;
861 let taken = self.marks.iter().any(|mark| {
862 matches!(mark.kind, MarkKind::Code | MarkKind::Link(_)) && overlaps(&mark.range, &range)
863 });
864 let Some(url) = link_url(&self.text[range.clone()]).filter(|_| !taken) else {
865 return false;
866 };
867 self.add_mark(range, MarkKind::Link(url));
868 true
869 }
870
871 /// Enter (or Shift+Enter) inside a list, quote or code block, or after a ``` fence.
872 /// `None` leaves the key to the caller: send, or a plain newline.
873 pub fn break_line(&mut self, cursor: usize, shift: bool) -> Option<usize> {
874 self.journal = Journal::default();
875 let index = self.line_at(cursor);
876 let kind = self.lines[index].clone();
877 let content = self.content_range(index);
878 let cursor = cursor.max(content.start);
879 match kind {
880 LineKind::Text => {
881 let language = fence_language(&self.text[content.clone()])?;
882 self.splice(content.clone(), "", &[]);
883 Some(self.set_line_kind(index, LineKind::Code(language), None, content.start))
884 }
885 LineKind::Heading(_) | LineKind::Table(_) | LineKind::Rule => None,
886 LineKind::Indent(_) if !shift => None,
887 LineKind::Indent(_) => {
888 self.splice(cursor..cursor, "\n", &[]);
889 self.lines[index + 1] = kind;
890 Some(cursor + 1)
891 }
892 LineKind::Quote if content.is_empty() && !shift => {
893 self.lines[index] = LineKind::Text;
894 Some(cursor)
895 }
896 LineKind::Quote => {
897 self.splice(cursor..cursor, "\n", &[]);
898 self.lines[index] = LineKind::Quote;
899 self.lines[index + 1] = LineKind::Quote;
900 Some(cursor + 1)
901 }
902 LineKind::Code(_) => {
903 let last_of_block = self.lines.get(index + 1) != Some(&kind);
904 let block_continues_above = index > 0 && self.lines[index - 1] == kind;
905 if content.is_empty() && last_of_block && block_continues_above && !shift {
906 return Some(self.set_line_kind(index, LineKind::Text, None, cursor));
907 }
908 self.splice(cursor..cursor, "\n", &[]);
909 Some(cursor + 1)
910 }
911 list => {
912 if self.text[content.clone()].trim().is_empty() {
913 let lifted = match list.depth() {
914 0 => LineKind::Text,
915 depth => list.with_depth(depth - 1),
916 };
917 let cursor = self.set_line_kind(index, lifted, None, cursor);
918 return Some(self.repair(cursor));
919 }
920 self.splice(cursor..cursor, "\n", &[]);
921 self.lines[index + 1] = list;
922 let marker = self.expected_marker(index + 1, None);
923 self.splice(cursor + 1..cursor + 1, &marker, &[]);
924 Some(self.repair(cursor + 1 + marker.len()))
925 }
926 }
927 }
928
929 /// Forward Delete next to a marker: at a line end it joins the next line without its
930 /// marker; inside a marker it deletes the first character of the content instead.
931 pub fn delete_forward(&mut self, cursor: usize) -> Option<usize> {
932 self.journal = Journal::default();
933 let index = self.line_at(cursor);
934 let line = self.line_ranges()[index].clone();
935 let content = self.content_range(index);
936 if cursor >= line.start && cursor < content.start {
937 let next = self.text[content.start..]
938 .chars()
939 .next()
940 .filter(|character| *character != '\n');
941 match next {
942 Some(character) => {
943 self.splice(content.start..content.start + character.len_utf8(), "", &[]);
944 }
945 None if index + 1 < self.lines.len() => {
946 let next_content = self.content_range(index + 1);
947 self.splice(content.end..next_content.start, "", &[]);
948 }
949 None => return Some(content.start),
950 }
951 return Some(self.repair(content.start));
952 }
953 if cursor != line.end || index + 1 >= self.lines.len() {
954 return None;
955 }
956 if self.lines[index + 1].is_table() {
957 return Some(cursor);
958 }
959 if self.lines[index + 1] == LineKind::Rule {
960 let rule = self.line_ranges()[index + 1].clone();
961 self.splice(cursor..rule.end, "", &[]);
962 return Some(self.repair(cursor));
963 }
964 let next_marker = self.marker_range(index + 1);
965 if next_marker.is_empty() {
966 return None;
967 }
968 self.splice(cursor..next_marker.end, "", &[]);
969 Some(self.repair(cursor))
970 }
971
972 /// Backspace at the start of a formatted line drops (or lifts) its format.
973 pub fn backspace_at_start(&mut self, cursor: usize) -> Option<usize> {
974 self.journal = Journal::default();
975 let index = self.line_at(cursor);
976 let kind = self.lines[index].clone();
977 let line = self.line_ranges()[index].clone();
978 let content = self.content_range(index);
979 if cursor == line.start && index > 0 && self.lines[index - 1] == LineKind::Rule {
980 let rule = self.line_ranges()[index - 1].clone();
981 self.splice(rule.start..line.start, "", &[]);
982 self.lines[index - 1] = kind;
983 return Some(self.repair(rule.start));
984 }
985 match &kind {
986 LineKind::Text | LineKind::Indent(_) | LineKind::Rule => None,
987 LineKind::Code(_) => {
988 let first_of_block = index == 0 || self.lines[index - 1] != kind;
989 (cursor == line.start && first_of_block).then(|| {
990 self.lines[index] = LineKind::Text;
991 cursor
992 })
993 }
994 LineKind::Table(_) => None,
995 LineKind::Heading(_) => (cursor == line.start).then(|| {
996 self.lines[index] = LineKind::Text;
997 cursor
998 }),
999 LineKind::Quote
1000 if cursor == line.start && (index == 0 || self.lines[index - 1] != kind) =>
1001 {
1002 let joins_previous =
1003 index > 0 && !content.is_empty() && !self.lines[index - 1].is_table();
1004 if !joins_previous {
1005 self.lines[index] = LineKind::Text;
1006 return Some(cursor);
1007 }
1008 self.splice(line.start - 1..line.start, "", &[]);
1009 Some(self.repair(line.start - 1))
1010 }
1011 _ if cursor == line.start && index > 0 => {
1012 self.splice(line.start - 1..content.start, "", &[]);
1013 Some(self.repair(line.start - 1))
1014 }
1015 _ if cursor > line.start && cursor <= content.start => {
1016 let lifted = match kind.depth() {
1017 depth if depth > 0 => kind.with_depth(depth - 1),
1018 _ => LineKind::Text,
1019 };
1020 let cursor = self.set_line_kind(index, lifted, None, cursor);
1021 Some(self.repair(cursor))
1022 }
1023 _ => None,
1024 }
1025 }
1026
1027 /// Tab / Shift+Tab on list lines. `false` when a selected line is not a list item.
1028 pub fn indent(&mut self, range: Range<usize>, outdent: bool) -> bool {
1029 self.journal = Journal::default();
1030 let lines = self.selected_lines(&range);
1031 if !lines.clone().all(|index| self.lines[index].is_list()) {
1032 return false;
1033 }
1034 for index in lines {
1035 let kind = self.lines[index].clone();
1036 let depth = kind.depth();
1037 let target = match (outdent, depth) {
1038 (true, 0) => LineKind::Text,
1039 (true, depth) => kind.with_depth(depth - 1),
1040 (false, depth) => kind.with_depth((depth + 1).min(MAX_DEPTH)),
1041 };
1042 self.set_line_kind(index, target, None, 0);
1043 }
1044 self.repair(0);
1045 true
1046 }
1047
1048 /// Teams' Increase / Decrease indent: list items nest or lift, paragraphs move by one
1049 /// block indent step.
1050 pub fn indent_blocks(&mut self, range: Range<usize>, outdent: bool) {
1051 self.journal = Journal::default();
1052 for index in self.selected_lines(&range) {
1053 let kind = self.lines[index].clone();
1054 let target = match (&kind, outdent) {
1055 (list, _) if list.is_list() => match (outdent, list.depth()) {
1056 (true, 0) => LineKind::Text,
1057 (true, depth) => list.with_depth(depth - 1),
1058 (false, depth) => list.with_depth((depth + 1).min(MAX_DEPTH)),
1059 },
1060 (LineKind::Text, false) => LineKind::Indent(1),
1061 (LineKind::Indent(level), false) => LineKind::Indent((level + 1).min(MAX_INDENT)),
1062 (LineKind::Indent(1), true) => LineKind::Text,
1063 (LineKind::Indent(level), true) => LineKind::Indent(level - 1),
1064 _ => continue,
1065 };
1066 self.set_line_kind(index, target, None, 0);
1067 }
1068 self.repair(0);
1069 }
1070
1071 /// Decrease indent has something to lift: a list item or an indented paragraph.
1072 pub fn can_outdent(&self, range: Range<usize>) -> bool {
1073 self.selected_lines(&range).any(|index| {
1074 self.lines[index].is_list() || matches!(self.lines[index], LineKind::Indent(_))
1075 })
1076 }
1077
1078 /// Teams' paragraph style: `None` is Paragraph, otherwise Heading 1 to 3.
1079 pub fn set_heading(&mut self, range: Range<usize>, level: Option<u8>) {
1080 self.journal = Journal::default();
1081 let target = level.map_or(LineKind::Text, |level| {
1082 LineKind::Heading(level.clamp(1, MAX_HEADING))
1083 });
1084 for index in self.selected_lines(&range) {
1085 let current = &self.lines[index];
1086 if current.object_mark().is_some() || matches!(current, LineKind::Code(_)) {
1087 continue;
1088 }
1089 if *current != target {
1090 self.set_line_kind(index, target.clone(), None, 0);
1091 }
1092 }
1093 self.repair(0);
1094 }
1095
1096 /// The paragraph style of the cursor's line: `None` for Paragraph.
1097 pub fn heading_at(&self, offset: usize) -> Option<u8> {
1098 match self.lines[self.line_at(offset)] {
1099 LineKind::Heading(level) => Some(level),
1100 _ => None,
1101 }
1102 }
1103
1104 /// The rule goes in place of an empty text line, otherwise below the cursor's line; the
1105 /// cursor goes to the text line after it, added when the rule ends the draft.
1106 pub fn insert_rule(&mut self, cursor: usize) -> usize {
1107 self.journal = Journal::default();
1108 let index = self.line_at(cursor);
1109 let line = self.line_ranges()[index].clone();
1110 let mark = RULE_MARK.to_string();
1111 let replaces_line = self.lines[index] == LineKind::Text && line.is_empty();
1112 let rule_index = if replaces_line {
1113 self.splice(line, &mark, &[]);
1114 index
1115 } else {
1116 self.splice(line.end..line.end, &format!("\n{mark}"), &[]);
1117 index + 1
1118 };
1119 self.lines[rule_index] = LineKind::Rule;
1120 if rule_index + 1 == self.lines.len() {
1121 let end = self.text.len();
1122 self.splice(end..end, "\n", &[]);
1123 self.lines[rule_index + 1] = LineKind::Text;
1124 }
1125 self.line_ranges()[rule_index + 1].start
1126 }
1127
1128 /// All selected lines `kind` already: back to text. Otherwise all become `kind`.
1129 pub fn toggle_lines(&mut self, range: Range<usize>, kind: LineKind) {
1130 self.journal = Journal::default();
1131 let lines = self.selected_lines(&range);
1132 let all = lines
1133 .clone()
1134 .all(|index| self.lines[index].same_format(&kind));
1135 for index in lines {
1136 let current = self.lines[index].clone();
1137 if current.is_table() {
1138 continue;
1139 }
1140 let target = if all {
1141 LineKind::Text
1142 } else if current.same_format(&kind) {
1143 current.clone()
1144 } else if current.is_list() && kind.is_list() {
1145 kind.with_depth(current.depth())
1146 } else {
1147 kind.clone()
1148 };
1149 if target != current {
1150 self.set_line_kind(index, target, None, 0);
1151 }
1152 }
1153 self.repair(0);
1154 }
1155
1156 pub fn table(&self, index: usize) -> Option<&Table> {
1157 match self.lines.get(index)? {
1158 LineKind::Table(table) => Some(table),
1159 _ => None,
1160 }
1161 }
1162
1163 /// Cell edits change no text, so the journal stays as it is.
1164 pub fn set_table(&mut self, index: usize, table: Table) {
1165 if let Some(kind @ LineKind::Table(_)) = self.lines.get_mut(index) {
1166 *kind = LineKind::Table(table);
1167 }
1168 }
1169
1170 /// The table goes in place of an empty text line, otherwise below the cursor's line, and
1171 /// a text line follows it. Returns the table's line.
1172 pub fn insert_table(&mut self, cursor: usize, table: Table) -> usize {
1173 self.journal = Journal::default();
1174 let index = self.line_at(cursor);
1175 let line = self.line_ranges()[index].clone();
1176 let mark = TABLE_MARK.to_string();
1177 let replaces_line = self.lines[index] == LineKind::Text && line.is_empty();
1178 let table_index = if replaces_line {
1179 self.splice(line, &mark, &[]);
1180 index
1181 } else {
1182 self.splice(line.end..line.end, &format!("\n{mark}"), &[]);
1183 index + 1
1184 };
1185 self.lines[table_index] = LineKind::Table(table);
1186 if table_index + 1 == self.lines.len() {
1187 let end = self.text.len();
1188 self.splice(end..end, "\n", &[]);
1189 self.lines[table_index + 1] = LineKind::Text;
1190 }
1191 table_index
1192 }
1193
1194 /// Returns where the cursor goes: the start of the line that took the table's place.
1195 pub fn remove_table(&mut self, index: usize) -> usize {
1196 self.journal = Journal::default();
1197 let ranges = self.line_ranges();
1198 let line = ranges[index].clone();
1199 if let Some(next) = ranges.get(index + 1) {
1200 let next_kind = self.lines[index + 1].clone();
1201 self.splice(line.start..next.start, "", &[]);
1202 self.lines[index] = next_kind;
1203 return self.repair(line.start);
1204 }
1205 if index > 0 {
1206 let start = ranges[index - 1].end;
1207 self.splice(start..line.end, "", &[]);
1208 return self.repair(start);
1209 }
1210 self.splice(line, "", &[]);
1211 self.lines[index] = LineKind::Text;
1212 0
1213 }
1214
1215 /// Where the cursor lands when it leaves table `index` downwards or upwards; a text line
1216 /// is added when the table is the last or the first line.
1217 pub fn line_beside_table(&mut self, index: usize, below: bool) -> usize {
1218 self.journal = Journal::default();
1219 let ranges = self.line_ranges();
1220 if below {
1221 if let Some(next) = ranges.get(index + 1) {
1222 return next.start;
1223 }
1224 let end = self.text.len();
1225 self.splice(end..end, "\n", &[]);
1226 self.lines[index + 1] = LineKind::Text;
1227 return end + 1;
1228 }
1229 if index > 0 {
1230 return ranges[index - 1].end;
1231 }
1232 self.splice(0..0, "\n", &[]);
1233 self.lines[0] = LineKind::Text;
1234 0
1235 }
1236
1237 pub fn table_at(&self, offset: usize) -> Option<usize> {
1238 let index = self.line_at(offset);
1239 self.lines[index].is_table().then_some(index)
1240 }
1241
1242 /// The table right above, when `cursor` is at the start of its line.
1243 pub fn table_before(&self, cursor: usize) -> Option<usize> {
1244 let index = self.line_at(cursor);
1245 let at_start = self.line_ranges()[index].start == cursor;
1246 (at_start && index > 0 && self.lines[index - 1].is_table()).then(|| index - 1)
1247 }
1248
1249 /// The table right below, when `cursor` is at the end of its line.
1250 pub fn table_after(&self, cursor: usize) -> Option<usize> {
1251 let index = self.line_at(cursor);
1252 let at_end = self.line_ranges()[index].end == cursor;
1253 (at_end && self.lines.get(index + 1).is_some_and(LineKind::is_table)).then_some(index + 1)
1254 }
1255
1256 /// Down or Right at the very end of a quote that ends the draft: a text line below it,
1257 /// like the empty paragraph Teams keeps after a quote.
1258 pub fn leave_quote_at_end(&mut self, cursor: usize) -> Option<usize> {
1259 self.journal = Journal::default();
1260 let end = self.text.len();
1261 let last = self.lines.len() - 1;
1262 if cursor != end || self.lines[last] != LineKind::Quote {
1263 return None;
1264 }
1265 self.splice(end..end, "\n", &[]);
1266 self.lines[last + 1] = LineKind::Text;
1267 Some(end + 1)
1268 }
1269
1270 pub fn slice(&self, range: Range<usize>) -> Vec<DraftLine> {
1271 let mut lines = Vec::new();
1272 for (index, line) in self.line_ranges().into_iter().enumerate() {
1273 if line.end < range.start || line.start > range.end {
1274 continue;
1275 }
1276 let content = self.content_range(index);
1277 let whole_start = range.start <= content.start;
1278 let start = range.start.max(content.start);
1279 let end = range.end.min(content.end).max(start);
1280 let kind = if whole_start {
1281 self.lines[index].clone()
1282 } else {
1283 LineKind::Text
1284 };
1285 let number = match kind {
1286 LineKind::Numbered(_) => {
1287 numbered_marker(&self.text[line.clone()]).map(|(_, number)| number)
1288 }
1289 _ => None,
1290 };
1291 let marks = self
1292 .marks
1293 .iter()
1294 .filter_map(|mark| {
1295 let clipped = mark.range.start.max(start)..mark.range.end.min(end);
1296 (!clipped.is_empty()).then(|| Mark {
1297 range: clipped.start - start..clipped.end - start,
1298 kind: mark.kind.clone(),
1299 })
1300 })
1301 .collect();
1302 lines.push(DraftLine {
1303 kind,
1304 number,
1305 content: self.text[start..end].to_owned(),
1306 marks,
1307 });
1308 }
1309 lines
1310 }
1311
1312 pub fn slice_without_objects(&self, range: Range<usize>) -> Vec<DraftLine> {
1313 let mut copy = Draft::from_lines(&self.slice(range));
1314 let marks: Vec<usize> = copy
1315 .text
1316 .match_indices(OBJECT_MARK)
1317 .map(|(index, _)| index)
1318 .collect();
1319 for index in marks.into_iter().rev() {
1320 copy.replace(index..index + OBJECT_MARK.len_utf8(), "");
1321 }
1322 copy.slice(0..usize::MAX)
1323 }
1324
1325 /// Puts `lines` in place of `range`. Returns the offset after the inserted content.
1326 pub fn insert_lines(&mut self, range: Range<usize>, lines: &[DraftLine]) -> usize {
1327 self.journal = Journal::default();
1328 let index = self.line_at(range.start);
1329 let content = self.content_range(index);
1330 let start = range.start.max(content.start);
1331 let range = start..range.end.max(start);
1332 let tail_end = self.line_ranges()[self.line_at(range.end)].end;
1333 let line_was_empty = self.lines[index] == LineKind::Text
1334 && range.start == content.start
1335 && range.end >= tail_end;
1336 let separated;
1337 let lines = if !line_was_empty && lines.first().is_some_and(|line| line.kind.is_table()) {
1338 separated = [&[DraftLine::text("")][..], lines].concat();
1339 &separated[..]
1340 } else {
1341 lines
1342 };
1343 let joined = lines
1344 .iter()
1345 .map(|line| line.content.as_str())
1346 .collect::<Vec<_>>()
1347 .join("\n");
1348 self.splice(range.clone(), &joined, &[]);
1349 let mut offset = range.start;
1350 for line in lines {
1351 for mark in &line.marks {
1352 self.add_mark(
1353 offset + mark.range.start..offset + mark.range.end,
1354 mark.kind.clone(),
1355 );
1356 }
1357 offset += line.content.len() + 1;
1358 }
1359 let length_before_markers = self.text.len();
1360 for (position, line) in lines.iter().enumerate() {
1361 let first_and_kept = position == 0 && !line_was_empty;
1362 if first_and_kept || line.kind == self.lines[index + position] {
1363 continue;
1364 }
1365 self.set_line_kind(index + position, line.kind.clone(), line.number, 0);
1366 }
1367 let end =
1368 (range.start + joined.len() + self.text.len()).saturating_sub(length_before_markers);
1369 self.repair(end)
1370 }
1371
1372 /// Leading and trailing blank lines and spaces dropped.
1373 pub fn trimmed(&self) -> Draft {
1374 let mut lines = self.slice(0..self.text.len());
1375 let blank =
1376 |line: &DraftLine| line.kind == LineKind::Text && line.content.trim().is_empty();
1377 while lines.len() > 1 && lines.first().is_some_and(blank) {
1378 lines.remove(0);
1379 }
1380 while lines.len() > 1 && lines.last().is_some_and(blank) {
1381 lines.pop();
1382 }
1383 if let Some(first) = lines.first_mut().filter(|line| line.kind == LineKind::Text) {
1384 first.trim_start();
1385 }
1386 if let Some(last) = lines
1387 .last_mut()
1388 .filter(|line| !matches!(line.kind, LineKind::Code(_)))
1389 {
1390 last.trim_end();
1391 }
1392 Draft::from_lines(&lines)
1393 }
1394
1395 /// Teams chat HTML.
1396 pub fn to_html(&self) -> String {
1397 let lines = self.slice(0..self.text.len());
1398 let mut html = String::new();
1399 let mut index = 0;
1400 while index < lines.len() {
1401 let kind = &lines[index].kind;
1402 let run_end = index
1403 + lines[index..]
1404 .iter()
1405 .take_while(|line| match kind {
1406 LineKind::Code(_) => line.kind == *kind,
1407 _ if kind.is_list() => line.kind.is_list(),
1408 _ => line.kind.same_format(kind),
1409 })
1410 .count();
1411 let run = &lines[index..run_end];
1412 match kind {
1413 LineKind::Text => html.push_str(&joined_inline(run)),
1414 LineKind::Quote => {
1415 html.push_str("<blockquote>");
1416 html.push_str(&joined_inline(run));
1417 html.push_str("</blockquote>");
1418 }
1419 LineKind::Heading(_) => {
1420 for line in run {
1421 let level = match line.kind {
1422 LineKind::Heading(level) => level.clamp(1, MAX_HEADING),
1423 _ => 1,
1424 };
1425 let inline = inline_html(&line.content, &line.marks);
1426 html.push_str(&format!("<h{level}>{inline}</h{level}>"));
1427 }
1428 }
1429 LineKind::Indent(_) => {
1430 for line in run {
1431 let level = match line.kind {
1432 LineKind::Indent(level) => u32::from(level.clamp(1, MAX_INDENT)),
1433 _ => 1,
1434 };
1435 let inline = inline_html(&line.content, &line.marks);
1436 let margin = level * INDENT_PIXELS;
1437 html.push_str(&format!(
1438 "<p style=\"margin-left:{margin}px;\">{inline}</p>"
1439 ));
1440 }
1441 }
1442 LineKind::Table(_) => {
1443 for line in run {
1444 if let LineKind::Table(table) = &line.kind {
1445 html.push_str(&table.to_html());
1446 }
1447 }
1448 }
1449 LineKind::Rule => html.push_str(&RULE_HTML.repeat(run.len())),
1450 LineKind::Code(language) => {
1451 let language = language.as_deref().unwrap_or(PLAIN_LANGUAGE);
1452 html.push_str(&format!(
1453 "<pre class=\"language-{} skipProofing\" spellcheck=\"false\"><code>",
1454 escape_html(&language.to_ascii_lowercase())
1455 ));
1456 let code = run
1457 .iter()
1458 .map(|line| escape_html(&line.content))
1459 .collect::<Vec<_>>()
1460 .join("<br>");
1461 html.push_str(&code);
1462 html.push_str("</code></pre>");
1463 }
1464 _ => html.push_str(&list_html(run)),
1465 }
1466 index = run_end;
1467 }
1468 html
1469 }
1470
1471 fn style_for_insertion(&self, start: usize, old_end: usize) -> Vec<MarkKind> {
1472 let mut kinds: Vec<MarkKind> = self
1473 .marks
1474 .iter()
1475 .filter(|mark| {
1476 let range = &mark.range;
1477 if old_end > start {
1478 range.start <= start && start < range.end
1479 } else {
1480 (range.start < start && start < range.end)
1481 || (range.start < start
1482 && range.end == start
1483 && mark.kind.continues_at_end())
1484 }
1485 })
1486 .map(|mark| mark.kind.clone())
1487 .collect();
1488 kinds.sort();
1489 kinds.dedup();
1490 kinds
1491 }
1492
1493 fn auto_link_urls(&self, range: &Range<usize>) -> Vec<String> {
1494 self.marks
1495 .iter()
1496 .filter_map(|mark| match &mark.kind {
1497 MarkKind::Link(url)
1498 if mark.range.start <= range.end
1499 && range.start <= mark.range.end
1500 && autolink_prefix(&self.text[mark.range.clone()]).is_some()
1501 && link_url(&self.text[mark.range.clone()]).as_ref() == Some(url) =>
1502 {
1503 Some(url.clone())
1504 }
1505 _ => None,
1506 })
1507 .collect()
1508 }
1509
1510 fn retarget_links(&mut self, auto_urls: &[String], edited: &Range<usize>) {
1511 if auto_urls.is_empty() {
1512 return;
1513 }
1514 let mut kept = Vec::with_capacity(self.marks.len());
1515 for mark in std::mem::take(&mut self.marks) {
1516 let touched = mark.range.start <= edited.end && edited.start <= mark.range.end;
1517 match &mark.kind {
1518 MarkKind::Link(url) if touched && auto_urls.contains(url) => {
1519 if let Some(new_url) = link_url(&self.text[mark.range.clone()]) {
1520 kept.push(Mark {
1521 range: mark.range,
1522 kind: MarkKind::Link(new_url),
1523 });
1524 }
1525 }
1526 _ => kept.push(mark),
1527 }
1528 }
1529 self.marks = kept;
1530 self.normalize_marks();
1531 }
1532
1533 fn content_parts(&self, range: Range<usize>) -> Vec<Range<usize>> {
1534 (self.line_at(range.start)..=self.line_at(range.end))
1535 .map(|index| {
1536 let content = self.content_range(index);
1537 content.start.max(range.start)..content.end.min(range.end)
1538 })
1539 .filter(|part| !part.is_empty())
1540 .collect()
1541 }
1542
1543 /// Links with a scheme other than http, https or mailto stay plain text.
1544 fn add_mark(&mut self, range: Range<usize>, kind: MarkKind) {
1545 let kind = match kind {
1546 MarkKind::Link(url) => match link_url(&url) {
1547 Some(url) => MarkKind::Link(url),
1548 None => return,
1549 },
1550 other => other,
1551 };
1552 if !range.is_empty() {
1553 self.marks.push(Mark { range, kind });
1554 self.normalize_marks();
1555 }
1556 }
1557
1558 fn remove_marks(&mut self, range: Range<usize>, kind: &MarkKind) {
1559 let mut kept = Vec::with_capacity(self.marks.len());
1560 for mark in std::mem::take(&mut self.marks) {
1561 if !mark.kind.same_format(kind) || !overlaps(&mark.range, &range) {
1562 kept.push(mark);
1563 continue;
1564 }
1565 if mark.range.start < range.start {
1566 kept.push(Mark {
1567 range: mark.range.start..range.start,
1568 kind: mark.kind.clone(),
1569 });
1570 }
1571 if mark.range.end > range.end {
1572 kept.push(Mark {
1573 range: range.end..mark.range.end,
1574 kind: mark.kind,
1575 });
1576 }
1577 }
1578 self.marks = kept;
1579 self.normalize_marks();
1580 }
1581
1582 fn normalize_marks(&mut self) {
1583 let length = self.text.len();
1584 let mut marks: Vec<Mark> = std::mem::take(&mut self.marks)
1585 .into_iter()
1586 .map(|mark| Mark {
1587 range: mark.range.start.min(length)..mark.range.end.min(length),
1588 kind: mark.kind,
1589 })
1590 .filter(|mark| !mark.range.is_empty())
1591 .collect();
1592 marks.sort_by(|left, right| {
1593 left.kind
1594 .cmp(&right.kind)
1595 .then(left.range.start.cmp(&right.range.start))
1596 });
1597 let mut merged: Vec<Mark> = Vec::with_capacity(marks.len());
1598 for mark in marks {
1599 match merged.last_mut() {
1600 Some(last) if last.kind == mark.kind && mark.range.start <= last.range.end => {
1601 last.range.end = last.range.end.max(mark.range.end);
1602 }
1603 _ => merged.push(mark),
1604 }
1605 }
1606 self.marks = merged;
1607 }
1608
1609 fn splice(&mut self, range: Range<usize>, replacement: &str, kinds: &[MarkKind]) {
1610 let (start, old_end) = (range.start, range.end);
1611 let first_line = self.line_at(start);
1612 let last_line = self.line_at(old_end);
1613 let line_start = self.line_ranges()[first_line].start;
1614 let breaks = replacement.matches('\n').count();
1615 let kind = self.lines[first_line].clone();
1616 let mut new_kinds = Vec::with_capacity(breaks + 1);
1617 let pushes_line_down = breaks > 0
1618 && start == line_start
1619 && old_end == start
1620 && !matches!(kind, LineKind::Code(_))
1621 && self.text[start..]
1622 .chars()
1623 .next()
1624 .is_some_and(|next| next != '\n');
1625 if pushes_line_down {
1626 new_kinds.extend(std::iter::repeat_n(LineKind::Text, breaks));
1627 new_kinds.push(kind);
1628 } else {
1629 let continued = match &kind {
1630 LineKind::Code(language) => LineKind::Code(language.clone()),
1631 _ => LineKind::Text,
1632 };
1633 new_kinds.push(kind);
1634 new_kinds.extend(std::iter::repeat_n(continued, breaks));
1635 }
1636 self.lines.splice(first_line..=last_line, new_kinds);
1637 self.text.replace_range(range.clone(), replacement);
1638
1639 let inserted = replacement.len();
1640 let delta = inserted as isize - (old_end - start) as isize;
1641 let shift = |position: usize| (position as isize + delta) as usize;
1642 let map_start = |position: usize| {
1643 if position < start {
1644 position
1645 } else if position >= old_end {
1646 shift(position)
1647 } else {
1648 start + inserted
1649 }
1650 };
1651 let map_end = |position: usize| {
1652 if position <= start {
1653 position
1654 } else if position >= old_end {
1655 shift(position)
1656 } else {
1657 start
1658 }
1659 };
1660 for mark in &mut self.marks {
1661 mark.range = map_start(mark.range.start)..map_end(mark.range.end);
1662 }
1663 if inserted > 0 {
1664 let inserted_range = start..start + inserted;
1665 let mut kept = Vec::with_capacity(self.marks.len() + kinds.len());
1666 for mark in std::mem::take(&mut self.marks) {
1667 if !overlaps(&mark.range, &inserted_range) || kinds.contains(&mark.kind) {
1668 kept.push(mark);
1669 continue;
1670 }
1671 if mark.range.start < inserted_range.start {
1672 kept.push(Mark {
1673 range: mark.range.start..inserted_range.start,
1674 kind: mark.kind.clone(),
1675 });
1676 }
1677 if mark.range.end > inserted_range.end {
1678 kept.push(Mark {
1679 range: inserted_range.end..mark.range.end,
1680 kind: mark.kind,
1681 });
1682 }
1683 }
1684 kept.extend(kinds.iter().map(|kind| Mark {
1685 range: inserted_range.clone(),
1686 kind: kind.clone(),
1687 }));
1688 self.marks = kept;
1689 }
1690 self.normalize_marks();
1691 self.journal.record(range, inserted, &self.text);
1692 }
1693
1694 fn previous_number(&self, index: usize, depth: u8) -> Option<u32> {
1695 let ranges = self.line_ranges();
1696 for previous in (0..index).rev() {
1697 match &self.lines[previous] {
1698 LineKind::Numbered(previous_depth) if *previous_depth == depth => {
1699 return numbered_marker(&self.text[ranges[previous].clone()])
1700 .map(|(_, number)| number);
1701 }
1702 kind if kind.is_list() && kind.depth() > depth => continue,
1703 _ => return None,
1704 }
1705 }
1706 None
1707 }
1708
1709 fn expected_marker(&self, index: usize, own_number: Option<u32>) -> String {
1710 let kind = &self.lines[index];
1711 let number = match kind {
1712 LineKind::Numbered(depth) => match self.previous_number(index, *depth) {
1713 Some(previous) => previous + 1,
1714 None => own_number
1715 .or_else(|| {
1716 let line = self.line_ranges()[index].clone();
1717 numbered_marker(&self.text[line]).map(|(_, number)| number)
1718 })
1719 .unwrap_or(1),
1720 },
1721 _ => 1,
1722 };
1723 marker_text(kind, number)
1724 }
1725
1726 fn set_line_kind(
1727 &mut self,
1728 index: usize,
1729 kind: LineKind,
1730 number: Option<u32>,
1731 cursor: usize,
1732 ) -> usize {
1733 let marker = self.marker_range(index);
1734 self.lines[index] = kind;
1735 let expected = self.expected_marker(index, number);
1736 self.replace_marker(marker, &expected, cursor)
1737 }
1738
1739 fn replace_marker(&mut self, marker: Range<usize>, expected: &str, cursor: usize) -> usize {
1740 if self.text[marker.clone()] == *expected {
1741 return cursor;
1742 }
1743 self.splice(marker.clone(), expected, &[]);
1744 if cursor >= marker.end {
1745 cursor + expected.len() - marker.len()
1746 } else if cursor > marker.start {
1747 marker.start + expected.len()
1748 } else {
1749 cursor
1750 }
1751 }
1752
1753 /// A table or rule line holds its mark alone: text typed next to it moves to its own
1754 /// line, a mark without its line kind is dropped and a line without its mark becomes text.
1755 fn repair_objects(&mut self, mut cursor: usize) -> usize {
1756 let mut index = 0;
1757 while index < self.lines.len() {
1758 let line = self.line_ranges()[index].clone();
1759 let kind = self.lines[index].clone();
1760 let expected = kind.object_mark();
1761 let stray = self.text[line.clone()]
1762 .char_indices()
1763 .find(|(_, character)| {
1764 [TABLE_MARK, RULE_MARK].contains(character) && Some(*character) != expected
1765 });
1766 if let Some((at, character)) = stray {
1767 let mark = line.start + at..line.start + at + character.len_utf8();
1768 self.splice(mark.clone(), "", &[]);
1769 cursor = map_offset(&[(mark, String::new())], cursor);
1770 continue;
1771 }
1772 let Some(object_mark) = expected else {
1773 index += 1;
1774 continue;
1775 };
1776 let mark_length = object_mark.len_utf8();
1777 match self.text[line.clone()].find(object_mark) {
1778 None => self.lines[index] = LineKind::Text,
1779 Some(at) if at > 0 => {
1780 let split = line.start + at;
1781 self.splice(split..split, "\n", &[]);
1782 self.lines[index] = LineKind::Text;
1783 self.lines[index + 1] = kind;
1784 cursor += usize::from(cursor > split);
1785 }
1786 Some(_) if line.len() > mark_length => {
1787 let split = line.start + mark_length;
1788 self.splice(split..split, "\n", &[]);
1789 cursor += usize::from(cursor > split);
1790 }
1791 Some(_) => {}
1792 }
1793 index += 1;
1794 }
1795 cursor
1796 }
1797
1798 /// List items whose marker was edited away become text; numbered items are renumbered.
1799 fn repair(&mut self, cursor: usize) -> usize {
1800 let mut cursor = self.repair_objects(cursor);
1801 for index in 0..self.lines.len() {
1802 let kind = self.lines[index].clone();
1803 if !kind.is_list() {
1804 continue;
1805 }
1806 let line = self.line_ranges()[index].clone();
1807 let expected = self.expected_marker(index, None);
1808 let current = &self.text[line.clone()];
1809 if current.starts_with(&expected) {
1810 continue;
1811 }
1812 match numbered_marker(current) {
1813 Some((length, _)) if matches!(kind, LineKind::Numbered(_)) => {
1814 cursor =
1815 self.replace_marker(line.start..line.start + length, &expected, cursor);
1816 }
1817 _ => self.lines[index] = LineKind::Text,
1818 }
1819 }
1820 cursor
1821 }
1822}
1823
1824fn hex_color(color: u32) -> String {
1825 format!("#{:06X}", color & 0xFF_FFFF)
1826}
1827
1828fn overlaps(left: &Range<usize>, right: &Range<usize>) -> bool {
1829 left.start < right.end && right.start < left.end
1830}
1831
1832fn bullet_marker(depth: u8) -> String {
1833 format!("{} ", BULLETS[depth as usize % BULLETS.len()])
1834}
1835
1836fn marker_text(kind: &LineKind, number: u32) -> String {
1837 match kind {
1838 LineKind::Bullet(depth) => bullet_marker(*depth),
1839 LineKind::Numbered(_) => format!("{number}. "),
1840 LineKind::Text
1841 | LineKind::Indent(_)
1842 | LineKind::Quote
1843 | LineKind::Code(_)
1844 | LineKind::Heading(_)
1845 | LineKind::Table(_)
1846 | LineKind::Rule => String::new(),
1847 }
1848}
1849
1850fn marker_len(kind: &LineKind, line: &str) -> usize {
1851 match kind {
1852 LineKind::Bullet(depth) => {
1853 let marker = bullet_marker(*depth);
1854 if line.starts_with(&marker) {
1855 marker.len()
1856 } else {
1857 0
1858 }
1859 }
1860 LineKind::Numbered(_) => numbered_marker(line).map_or(0, |(length, _)| length),
1861 _ => 0,
1862 }
1863}
1864
1865/// Byte length and number of a `1. ` marker.
1866fn numbered_marker(line: &str) -> Option<(usize, u32)> {
1867 let digits = line.bytes().take_while(u8::is_ascii_digit).count();
1868 if digits == 0 || digits > 9 || !line[digits..].starts_with(". ") {
1869 return None;
1870 }
1871 Some((digits + 2, line[..digits].parse().ok()?))
1872}
1873
1874fn line_shortcut(before: &str) -> Option<(LineKind, u32)> {
1875 match before {
1876 "- " | "* " => Some((LineKind::Bullet(0), 1)),
1877 ">" => Some((LineKind::Quote, 1)),
1878 _ if before.starts_with('#') => heading_prefix(before)
1879 .and_then(|(level, rest)| rest.is_empty().then_some((LineKind::Heading(level), 1))),
1880 _ => {
1881 let digits = before.strip_suffix(". ")?;
1882 let all_digits = !digits.is_empty()
1883 && digits.len() <= 9
1884 && digits.bytes().all(|byte| byte.is_ascii_digit());
1885 all_digits.then(|| (LineKind::Numbered(0), digits.parse().unwrap_or(1)))
1886 }
1887 }
1888}
1889
1890fn fence_language(line: &str) -> Option<Option<String>> {
1891 let info = line.trim().strip_prefix(FENCE)?;
1892 let valid = info
1893 .chars()
1894 .all(|character| character.is_alphanumeric() || "+#-_.".contains(character));
1895 valid.then(|| (!info.is_empty()).then(|| info.to_lowercase()))
1896}
1897
1898fn valid_inner(inner: &str) -> bool {
1899 !inner.is_empty()
1900 && !inner.starts_with(char::is_whitespace)
1901 && !inner.ends_with(char::is_whitespace)
1902}
1903
1904fn word_before(text: &str) -> bool {
1905 text.chars()
1906 .next_back()
1907 .is_some_and(|character| character.is_alphanumeric())
1908}
1909
1910/// `https://` added when there is no scheme. `None` for any scheme but http, https and mailto.
1911pub fn link_url(text: &str) -> Option<String> {
1912 let text = text.trim();
1913 if text.is_empty() || text.contains(char::is_whitespace) {
1914 return None;
1915 }
1916 let lower = text.to_ascii_lowercase();
1917 if LINK_SCHEMES.iter().any(|scheme| lower.starts_with(scheme)) {
1918 return Some(text.to_owned());
1919 }
1920 let scheme = text.split_once(':').filter(|(scheme, rest)| {
1921 let host = scheme.contains('.') || scheme.eq_ignore_ascii_case("localhost");
1922 let host_and_port = host && rest.starts_with(|character: char| character.is_ascii_digit());
1923 !host_and_port
1924 && scheme.starts_with(|character: char| character.is_ascii_alphabetic())
1925 && scheme
1926 .chars()
1927 .all(|character| character.is_ascii_alphanumeric() || "+.-".contains(character))
1928 });
1929 scheme.is_none().then(|| format!("https://{text}"))
1930}
1931
1932fn autolink_prefix(text: &str) -> Option<&'static str> {
1933 AUTOLINK_PREFIXES.into_iter().find(|prefix| {
1934 text.get(..prefix.len())
1935 .is_some_and(|head| head.eq_ignore_ascii_case(prefix))
1936 })
1937}
1938
1939/// Length of the URL at the start of `rest`, when `previous` does not continue a word.
1940fn bare_url_at(rest: &str, previous: Option<char>) -> Option<usize> {
1941 if previous.is_some_and(char::is_alphanumeric) {
1942 return None;
1943 }
1944 bare_url_len(rest)
1945}
1946
1947/// Length of the URL a word starts with, without trailing punctuation.
1948fn bare_url_len(rest: &str) -> Option<usize> {
1949 let word = &rest[..rest.find(char::is_whitespace).unwrap_or(rest.len())];
1950 let prefix = autolink_prefix(word)?;
1951 let mut end = word.len();
1952 while let Some(last) = word[..end].chars().next_back() {
1953 let trailing = match last {
1954 ')' => word[..end].matches(')').count() > word[..end].matches('(').count(),
1955 other => AUTOLINK_TRAILING.contains(other),
1956 };
1957 if !trailing {
1958 break;
1959 }
1960 end -= last.len_utf8();
1961 }
1962 (end > prefix.len()).then_some(end)
1963}
1964
1965/// The markers of a format closed by the last typed character, relative to `before`.
1966fn typed_inline(before: &str) -> Option<(Range<usize>, Range<usize>, MarkKind)> {
1967 let end = before.len();
1968 if before.ends_with(')') {
1969 let captures = TYPED_LINK.captures(before)?;
1970 let whole = captures.get(0)?;
1971 let label = captures.get(1)?;
1972 return Some((
1973 whole.start()..whole.start() + 1,
1974 label.end()..end,
1975 MarkKind::Link(link_url(&captures[2])?),
1976 ));
1977 }
1978 for (marker, kind) in [("**", MarkKind::Bold), ("~~", MarkKind::Strike)] {
1979 if let Some(body) = before.strip_suffix(marker) {
1980 let open = body.rfind(marker)?;
1981 return valid_inner(&body[open + 2..]).then(|| (open..open + 2, body.len()..end, kind));
1982 }
1983 }
1984 if let Some(body) = before.strip_suffix('`') {
1985 let open = body.rfind('`')?;
1986 let usable = !body[open + 1..].trim().is_empty() && !body[..open].ends_with('`');
1987 return usable.then(|| (open..open + 1, body.len()..end, MarkKind::Code));
1988 }
1989 for (marker, kind) in [('*', MarkKind::Bold), ('_', MarkKind::Italic)] {
1990 if let Some(body) = before.strip_suffix(marker) {
1991 if body.ends_with(marker) {
1992 return None;
1993 }
1994 let open = body.rfind(marker)?;
1995 let opening_ok = !word_before(&body[..open]) && !body[..open].ends_with(marker);
1996 return (opening_ok && valid_inner(&body[open + 1..]))
1997 .then(|| (open..open + 1, body.len()..end, kind));
1998 }
1999 }
2000 None
2001}
2002
2003pub fn changed_span(old: &str, new: &str) -> (usize, usize, usize) {
2004 edit_span(old, new, new.len())
2005}
2006
2007fn edit_span(old: &str, new: &str, cursor: usize) -> (usize, usize, usize) {
2008 let prefix = old
2009 .char_indices()
2010 .zip(new.chars())
2011 .find(|((_, left), right)| left != right)
2012 .map_or(old.len().min(new.len()), |((index, _), _)| index);
2013 let prefix = {
2014 let mut prefix = prefix.min(old.len()).min(new.len());
2015 while !old.is_char_boundary(prefix) || !new.is_char_boundary(prefix) {
2016 prefix -= 1;
2017 }
2018 prefix
2019 };
2020 let suffix = old[prefix..]
2021 .chars()
2022 .rev()
2023 .zip(new[prefix..].chars().rev())
2024 .take_while(|(left, right)| left == right)
2025 .map(|(character, _)| character.len_utf8())
2026 .sum::<usize>();
2027 let (start, old_end, new_end) = (prefix, old.len() - suffix, new.len() - suffix);
2028 let cursor = cursor.min(new.len());
2029 let pure = old_end == start || new_end == start;
2030 if pure && new_end > cursor && new_end - cursor <= start {
2031 let slide = new_end - cursor;
2032 let (slid_start, slid_old_end, slid_new_end) =
2033 (start - slide, old_end - slide, new_end - slide);
2034 let boundaries = [slid_start, slid_old_end]
2035 .iter()
2036 .all(|offset| old.is_char_boundary(*offset))
2037 && [slid_start, slid_new_end]
2038 .iter()
2039 .all(|offset| new.is_char_boundary(*offset));
2040 if boundaries && new[slid_new_end..] == old[slid_old_end..] {
2041 return (slid_start, slid_old_end, slid_new_end);
2042 }
2043 }
2044 (start, old_end, new_end)
2045}
2046
2047fn joined_inline(lines: &[DraftLine]) -> String {
2048 lines
2049 .iter()
2050 .map(|line| inline_html(&line.content, &line.marks))
2051 .collect::<Vec<_>>()
2052 .join("<br>")
2053}
2054
2055/// The official client sends a link whose text is its own URL with the text cut to this many
2056/// characters, the last one an ellipsis; the full URL stays in `href` and `title`.
2057const LINK_TEXT_LIMIT: usize = 100;
2058const LINK_ELLIPSIS: char = '…';
2059
2060struct ShortenedLinks {
2061 content: String,
2062 marks: Vec<Mark>,
2063 urls: Vec<String>,
2064}
2065
2066/// Shortens the text of each link that spells out its own URL past `LINK_TEXT_LIMIT`.
2067fn shortened_links(content: &str, marks: &[Mark]) -> Option<ShortenedLinks> {
2068 let mut long: Vec<(Range<usize>, &String)> = marks
2069 .iter()
2070 .filter_map(|mark| match &mark.kind {
2071 MarkKind::Link(url) => {
2072 let text = content.get(mark.range.clone())?;
2073 let spells_url = text == url || link_url(text).as_ref() == Some(url);
2074 (spells_url && text.chars().count() > LINK_TEXT_LIMIT)
2075 .then(|| (mark.range.clone(), url))
2076 }
2077 _ => None,
2078 })
2079 .collect();
2080 if long.is_empty() {
2081 return None;
2082 }
2083 long.sort_by_key(|(range, _)| range.start);
2084 long.dedup();
2085 let urls = long.iter().map(|(_, url)| (*url).clone()).collect();
2086 let mut text = content.to_owned();
2087 let mut marks = marks.to_vec();
2088 for (range, _) in long.into_iter().rev() {
2089 let kept = content[range.clone()]
2090 .char_indices()
2091 .nth(LINK_TEXT_LIMIT - 1)
2092 .map_or(range.len(), |(offset, _)| offset);
2093 let cut = range.start + kept;
2094 let end = cut + LINK_ELLIPSIS.len_utf8();
2095 text.replace_range(cut..range.end, &LINK_ELLIPSIS.to_string());
2096 let moved = |offset: usize| {
2097 if offset <= cut {
2098 offset
2099 } else if offset >= range.end {
2100 offset - range.end + end
2101 } else {
2102 end
2103 }
2104 };
2105 for mark in &mut marks {
2106 mark.range = moved(mark.range.start)..moved(mark.range.end);
2107 }
2108 }
2109 marks.retain(|mark| !mark.range.is_empty());
2110 Some(ShortenedLinks {
2111 content: text,
2112 marks,
2113 urls,
2114 })
2115}
2116
2117fn inline_html(content: &str, marks: &[Mark]) -> String {
2118 if let Some(shortened) = shortened_links(content, marks) {
2119 return inline_html_exact(&shortened.content, &shortened.marks, &shortened.urls);
2120 }
2121 inline_html_exact(content, marks, &[])
2122}
2123
2124/// `titled` links carry their URL in `title` too, for the hover a shortened text needs.
2125fn inline_html_exact(content: &str, marks: &[Mark], titled: &[String]) -> String {
2126 let mut boundaries: Vec<usize> = marks
2127 .iter()
2128 .flat_map(|mark| [mark.range.start, mark.range.end])
2129 .chain([0, content.len()])
2130 .filter(|offset| *offset <= content.len())
2131 .collect();
2132 boundaries.sort_unstable();
2133 boundaries.dedup();
2134 let mut html = String::new();
2135 let mut open: Vec<&MarkKind> = Vec::new();
2136 for window in boundaries.windows(2) {
2137 let segment = window[0]..window[1];
2138 let mut active: Vec<&MarkKind> = marks
2139 .iter()
2140 .filter(|mark| mark.range.start <= segment.start && segment.end <= mark.range.end)
2141 .map(|mark| &mark.kind)
2142 .collect();
2143 active.sort();
2144 active.dedup();
2145 let common = open
2146 .iter()
2147 .zip(active.iter())
2148 .take_while(|(left, right)| left == right)
2149 .count();
2150 for kind in open.drain(common..).rev() {
2151 html.push_str(kind.close_tag());
2152 }
2153 for kind in &active[common..] {
2154 match kind {
2155 MarkKind::Link(url) if titled.contains(url) => {
2156 let url = escape_html(url);
2157 html.push_str(&format!("<a href=\"{url}\" title=\"{url}\">"));
2158 }
2159 _ => html.push_str(&kind.open_tag()),
2160 }
2161 }
2162 open.extend(active[common..].iter().copied());
2163 html.push_str(&escape_html(&content[segment]));
2164 }
2165 for kind in open.into_iter().rev() {
2166 html.push_str(kind.close_tag());
2167 }
2168 html
2169}
2170
2171fn list_html(lines: &[DraftLine]) -> String {
2172 let close = |ordered: bool| if ordered { "</li></ol>" } else { "</li></ul>" };
2173 let mut html = String::new();
2174 let mut open: Vec<(u8, bool)> = Vec::new();
2175 for line in lines {
2176 let ordered = matches!(line.kind, LineKind::Numbered(_));
2177 let depth = line
2178 .kind
2179 .depth()
2180 .min(open.last().map_or(0, |(depth, _)| depth + 1));
2181 while open
2182 .last()
2183 .is_some_and(|(open_depth, _)| *open_depth > depth)
2184 {
2185 let (_, was_ordered) = open.pop().unwrap_or_default();
2186 html.push_str(close(was_ordered));
2187 }
2188 match open.last().copied() {
2189 Some((open_depth, open_ordered)) if open_depth == depth && open_ordered == ordered => {
2190 html.push_str("</li>");
2191 }
2192 Some((open_depth, open_ordered)) if open_depth == depth => {
2193 html.push_str(close(open_ordered));
2194 open.pop();
2195 html.push_str(&list_open(ordered, line.number));
2196 open.push((depth, ordered));
2197 }
2198 _ => {
2199 html.push_str(&list_open(ordered, line.number));
2200 open.push((depth, ordered));
2201 }
2202 }
2203 html.push_str("<li>");
2204 html.push_str(&inline_html(&line.content, &line.marks));
2205 }
2206 for (_, ordered) in open.into_iter().rev() {
2207 html.push_str(close(ordered));
2208 }
2209 html
2210}
2211
2212fn list_open(ordered: bool, number: Option<u32>) -> String {
2213 match (ordered, number) {
2214 (false, _) => "<ul>".to_owned(),
2215 (true, Some(start)) if start != 1 => format!("<ol start=\"{start}\">"),
2216 (true, _) => "<ol>".to_owned(),
2217 }
2218}
2219
2220/// Text that `from_markdown` would format: pasting it converts.
2221pub fn has_markdown(text: &str) -> bool {
2222 let draft = Draft::from_markdown(text);
2223 !draft.marks.is_empty() || draft.lines.iter().any(|kind| *kind != LineKind::Text)
2224}
2225
2226fn markdown_lines(text: &str) -> Vec<DraftLine> {
2227 let sources: Vec<&str> = text
2228 .split('\n')
2229 .map(|raw| raw.strip_suffix('\r').unwrap_or(raw))
2230 .collect();
2231 let mut lines = Vec::new();
2232 let mut code: Option<Option<String>> = None;
2233 let mut position = 0;
2234 while position < sources.len() {
2235 let raw = sources[position];
2236 position += 1;
2237 let trimmed = raw.trim_start();
2238 if let Some(language) = &code {
2239 if trimmed.starts_with(FENCE) && trimmed.trim_end() == FENCE {
2240 code = None;
2241 } else {
2242 lines.push(DraftLine {
2243 kind: LineKind::Code(language.clone()),
2244 number: None,
2245 content: raw.to_owned(),
2246 marks: Vec::new(),
2247 });
2248 }
2249 continue;
2250 }
2251 if trimmed.starts_with(FENCE)
2252 && !trimmed[FENCE.len()..].contains('`')
2253 && let Some(language) = fence_language(trimmed)
2254 {
2255 code = Some(language);
2256 continue;
2257 }
2258 if let Some((rows, consumed)) = markdown_table(&sources[position - 1..]) {
2259 let rows = rows
2260 .into_iter()
2261 .map(|row| row.iter().map(|cell| parse_inline(cell).0).collect())
2262 .collect();
2263 lines.push(table_line(Table::from_rows(rows)));
2264 position += consumed - 1;
2265 continue;
2266 }
2267 let indent: usize = raw[..raw.len() - trimmed.len()]
2268 .chars()
2269 .map(|character| if character == '\t' { 4 } else { 1 })
2270 .sum();
2271 let depth = ((indent / MARKDOWN_INDENT) as u8).min(MAX_DEPTH);
2272 let (kind, number, content) = if let Some((level, rest)) = heading_prefix(trimmed) {
2273 (LineKind::Heading(level), None, rest)
2274 } else if let Some(rest) = PASTED_BULLETS
2275 .iter()
2276 .find_map(|bullet| trimmed.strip_prefix(bullet))
2277 {
2278 (LineKind::Bullet(depth), None, rest)
2279 } else if let Some((length, number)) = numbered_marker(trimmed) {
2280 (LineKind::Numbered(depth), Some(number), &trimmed[length..])
2281 } else if let Some(rest) = trimmed
2282 .strip_prefix("> ")
2283 .or_else(|| (trimmed == ">").then_some(""))
2284 {
2285 (LineKind::Quote, None, rest)
2286 } else {
2287 (LineKind::Text, None, raw)
2288 };
2289 let (content, marks) = parse_inline(content);
2290 lines.push(DraftLine {
2291 kind,
2292 number,
2293 content,
2294 marks,
2295 });
2296 }
2297 lines
2298}
2299
2300fn table_line(table: Table) -> DraftLine {
2301 DraftLine {
2302 kind: LineKind::Table(table),
2303 number: None,
2304 content: TABLE_MARK.to_string(),
2305 marks: Vec::new(),
2306 }
2307}
2308
2309/// `# ` to `###### `: the level, capped at the three Teams offers, and the rest of the line.
2310fn heading_prefix(line: &str) -> Option<(u8, &str)> {
2311 let hashes = line.bytes().take_while(|byte| *byte == b'#').count();
2312 let rest = line[hashes..].strip_prefix(' ')?;
2313 (1..=6)
2314 .contains(&hashes)
2315 .then(|| ((hashes as u8).min(MAX_HEADING), rest))
2316}
2317
2318fn parse_inline(source: &str) -> (String, Vec<Mark>) {
2319 let mut text = String::with_capacity(source.len());
2320 let mut marks = Vec::new();
2321 parse_into(source, &mut text, &mut marks, true);
2322 (text, marks)
2323}
2324
2325fn parse_into(source: &str, text: &mut String, marks: &mut Vec<Mark>, autolink: bool) {
2326 let mut rest = source;
2327 let mut previous: Option<char> = None;
2328 while let Some(character) = rest.chars().next() {
2329 if autolink
2330 && let Some(length) = bare_url_at(rest, previous)
2331 && let Some(url) = link_url(&rest[..length])
2332 {
2333 let start = text.len();
2334 text.push_str(&rest[..length]);
2335 marks.push(Mark {
2336 range: start..text.len(),
2337 kind: MarkKind::Link(url),
2338 });
2339 previous = rest[..length].chars().next_back();
2340 rest = &rest[length..];
2341 continue;
2342 }
2343 if let Some((inner, consumed, kind)) = inline_at(rest, previous) {
2344 let start = text.len();
2345 match kind {
2346 MarkKind::Code => text.push_str(inner),
2347 MarkKind::Link(_) => parse_into(inner, text, marks, false),
2348 _ => parse_into(inner, text, marks, autolink),
2349 }
2350 marks.push(Mark {
2351 range: start..text.len(),
2352 kind,
2353 });
2354 previous = rest[..consumed].chars().next_back();
2355 rest = &rest[consumed..];
2356 continue;
2357 }
2358 text.push(character);
2359 previous = Some(character);
2360 rest = &rest[character.len_utf8()..];
2361 }
2362}
2363
2364/// A format starting at the beginning of `rest`: its inner text, the bytes it spans, its kind.
2365fn inline_at(rest: &str, previous: Option<char>) -> Option<(&str, usize, MarkKind)> {
2366 if let Some(after) = rest.strip_prefix('`') {
2367 let end = after.find('`')?;
2368 let inner = &after[..end];
2369 return (!inner.trim().is_empty()).then_some((inner, end + 2, MarkKind::Code));
2370 }
2371 if rest.starts_with('[') {
2372 let captures = LINK_AT.captures(rest)?;
2373 let label = captures.get(1)?;
2374 return Some((
2375 label.as_str(),
2376 captures.get(0)?.end(),
2377 MarkKind::Link(link_url(&captures[2])?),
2378 ));
2379 }
2380 for (marker, kind) in [("**", MarkKind::Bold), ("~~", MarkKind::Strike)] {
2381 if let Some(after) = rest.strip_prefix(marker) {
2382 let end = after.find(marker)?;
2383 let inner = &after[..end];
2384 return valid_inner(inner).then_some((inner, end + 4, kind));
2385 }
2386 }
2387 for marker in ['*', '_'] {
2388 let Some(after) = rest.strip_prefix(marker) else {
2389 continue;
2390 };
2391 if previous.is_some_and(char::is_alphanumeric) || after.starts_with(marker) {
2392 return None;
2393 }
2394 let end = after.find(marker)?;
2395 let inner = &after[..end];
2396 let followed_by_word = after[end + 1..]
2397 .chars()
2398 .next()
2399 .is_some_and(char::is_alphanumeric);
2400 return (valid_inner(inner) && !followed_by_word).then_some((
2401 inner,
2402 end + 2,
2403 MarkKind::Italic,
2404 ));
2405 }
2406 None
2407}
2408
2409fn cell_text(spans: &[Span]) -> String {
2410 let mut builder = SpanLines::default();
2411 builder.walk(spans, &LineKind::Text, &[]);
2412 builder
2413 .finish()
2414 .into_iter()
2415 .map(|line| line.content)
2416 .collect::<Vec<_>>()
2417 .join("\n")
2418}
2419
2420#[derive(Default)]
2421struct SpanLines {
2422 lines: Vec<DraftLine>,
2423 open: bool,
2424}
2425
2426impl SpanLines {
2427 fn start_line(&mut self, kind: &LineKind, number: Option<u32>) {
2428 self.lines.push(DraftLine {
2429 kind: kind.clone(),
2430 number,
2431 content: String::new(),
2432 marks: Vec::new(),
2433 });
2434 self.open = true;
2435 }
2436
2437 fn append(&mut self, text: &str, kind: &LineKind, marks: &[MarkKind]) {
2438 for (index, piece) in text.split('\n').enumerate() {
2439 if index > 0 || !self.open {
2440 self.start_line(kind, None);
2441 }
2442 let Some(line) = self.lines.last_mut() else {
2443 continue;
2444 };
2445 let start = line.content.len();
2446 line.content.push_str(piece);
2447 let end = line.content.len();
2448 if end > start {
2449 line.marks.extend(marks.iter().map(|kind| Mark {
2450 range: start..end,
2451 kind: kind.clone(),
2452 }));
2453 }
2454 }
2455 }
2456
2457 fn walk(&mut self, spans: &[Span], kind: &LineKind, marks: &[MarkKind]) {
2458 let with = |extra: MarkKind| {
2459 let mut marks = marks.to_vec();
2460 marks.push(extra);
2461 marks
2462 };
2463 for (index, span) in spans.iter().enumerate() {
2464 let block_follows = matches!(
2465 spans.get(index + 1),
2466 Some(
2467 Span::List { .. }
2468 | Span::BlockQuote(_)
2469 | Span::CodeBlock { .. }
2470 | Span::Heading { .. }
2471 | Span::Table { .. }
2472 | Span::Rule
2473 | Span::Indent { .. }
2474 )
2475 );
2476 match span {
2477 Span::Text(text) => self.append(text, kind, marks),
2478 Span::Bold(children) => self.walk(children, kind, &with(MarkKind::Bold)),
2479 Span::Italic(children) => self.walk(children, kind, &with(MarkKind::Italic)),
2480 Span::Strike(children) => self.walk(children, kind, &with(MarkKind::Strike)),
2481 Span::Underline(children) => self.walk(children, kind, &with(MarkKind::Underline)),
2482 Span::Superscript(children) => {
2483 self.walk(children, kind, &with(MarkKind::Superscript))
2484 }
2485 Span::Subscript(children) => self.walk(children, kind, &with(MarkKind::Subscript)),
2486 Span::Sized(FontSize::Small, children) => {
2487 self.walk(children, kind, &with(MarkKind::Size(SizeStep::Small)))
2488 }
2489 Span::Sized(FontSize::Large, children) => {
2490 self.walk(children, kind, &with(MarkKind::Size(SizeStep::Large)))
2491 }
2492 Span::Sized(_, children) => self.walk(children, kind, marks),
2493 Span::Colored {
2494 color,
2495 background,
2496 children,
2497 } => {
2498 let mut colored = marks.to_vec();
2499 colored.extend(color.map(MarkKind::Color));
2500 colored.extend(background.map(MarkKind::Highlight));
2501 self.walk(children, kind, &colored)
2502 }
2503 Span::Code(text) => self.append(text, kind, &with(MarkKind::Code)),
2504 Span::Link { url, children } => {
2505 self.walk(children, kind, &with(MarkKind::Link(url.clone())))
2506 }
2507 Span::Mention { name, .. } => {
2508 self.append(&format!("@{}", name.trim_start_matches('@')), kind, marks)
2509 }
2510 Span::Rule if *kind == LineKind::Text => {
2511 self.lines.push(DraftLine {
2512 kind: LineKind::Rule,
2513 number: None,
2514 content: RULE_MARK.to_string(),
2515 marks: Vec::new(),
2516 });
2517 self.open = false;
2518 }
2519 Span::Indent { level, children }
2520 if *kind == LineKind::Text
2521 && !children
2522 .iter()
2523 .any(|child| matches!(child, Span::Heading { .. })) =>
2524 {
2525 let indent = LineKind::Indent((*level).clamp(1, MAX_INDENT));
2526 self.start_line(&indent, None);
2527 self.walk(children, &indent, marks);
2528 self.open = false;
2529 }
2530 Span::Indent { children, .. } => self.walk(children, kind, marks),
2531 Span::LineBreak | Span::Rule if !self.open || block_follows => {}
2532 Span::LineBreak | Span::Rule => {
2533 let continued = match kind {
2534 LineKind::Quote | LineKind::Code(_) | LineKind::Indent(_) => kind.clone(),
2535 _ => LineKind::Text,
2536 };
2537 self.start_line(&continued, None);
2538 }
2539 Span::Heading { level, children } => {
2540 let heading = LineKind::Heading((*level).clamp(1, MAX_HEADING));
2541 self.start_line(&heading, None);
2542 self.walk(children, &heading, marks);
2543 self.open = false;
2544 }
2545 Span::CodeBlock { language, code } => {
2546 let code_kind = LineKind::Code(language.clone());
2547 for line in code.trim_end_matches('\n').split('\n') {
2548 self.start_line(&code_kind, None);
2549 self.append(line, &code_kind, &[]);
2550 }
2551 self.open = false;
2552 }
2553 Span::BlockQuote(children) => {
2554 self.start_line(&LineKind::Quote, None);
2555 self.walk(children, &LineKind::Quote, marks);
2556 self.open = false;
2557 }
2558 Span::List {
2559 ordered,
2560 start,
2561 items,
2562 } => {
2563 let depth = if kind.is_list() {
2564 (kind.depth() + 1).min(MAX_DEPTH)
2565 } else {
2566 0
2567 };
2568 let item_kind = if *ordered {
2569 LineKind::Numbered(depth)
2570 } else {
2571 LineKind::Bullet(depth)
2572 };
2573 for (position, item) in items.iter().enumerate() {
2574 let number = (position == 0).then_some(*start);
2575 self.start_line(&item_kind, number);
2576 self.walk(item, &item_kind, marks);
2577 }
2578 self.open = false;
2579 }
2580 Span::Table { rows, .. } => {
2581 let rows = rows
2582 .iter()
2583 .map(|row| row.iter().map(|cell| cell_text(cell)).collect())
2584 .collect();
2585 self.lines.push(table_line(Table::from_rows(rows)));
2586 self.open = false;
2587 }
2588 Span::Image { .. } | Span::Quote { .. } | Span::CustomEmoji { .. } => {}
2589 }
2590 }
2591 }
2592
2593 fn finish(mut self) -> Vec<DraftLine> {
2594 let blank =
2595 |line: &DraftLine| line.kind == LineKind::Text && line.content.trim().is_empty();
2596 while self.lines.len() > 1 && self.lines.last().is_some_and(blank) {
2597 self.lines.pop();
2598 }
2599 while self.lines.len() > 1 && self.lines.first().is_some_and(blank) {
2600 self.lines.remove(0);
2601 }
2602 if self.lines.is_empty() {
2603 self.lines.push(DraftLine::text(""));
2604 }
2605 self.lines
2606 }
2607}
2608
2609#[cfg(test)]
2610mod tests {
2611 use super::*;
2612 use crate::html_to_spans;
2613
2614 fn typed(draft: &mut Draft, text: &str) {
2615 let mut typing: Option<TypingStyle> = None;
2616 for character in text.chars() {
2617 let cursor = draft.text().len();
2618 let mut next = draft.text().to_owned();
2619 next.push(character);
2620 let cursor = draft.apply_edit(&next, cursor + character.len_utf8(), typing.as_ref());
2621 typing = draft.convert_typed(cursor).map(|(_, style)| style);
2622 draft.take_edits();
2623 }
2624 }
2625
2626 #[test]
2627 fn object_marks_stay_in_the_html_and_leave_the_plain_text() {
2628 let draft = Draft::plain("a \u{FFFC} b");
2629 assert_eq!(draft.plain_text(), "a b");
2630 assert_eq!(draft.to_html(), "a \u{FFFC} b");
2631 assert!(Draft::plain("\u{FFFC}").is_blank());
2632 }
2633
2634 #[test]
2635 fn slices_without_objects_keep_the_formatting_of_the_rest() {
2636 let mut draft = Draft::plain("ab\u{FFFC}cd");
2637 draft.toggle(0..draft.text().len(), MarkKind::Bold);
2638 let lines = draft.slice_without_objects(0..draft.text().len());
2639 assert_eq!(lines.len(), 1);
2640 assert_eq!(lines[0].content, "abcd");
2641 assert_eq!(
2642 lines[0].marks,
2643 [Mark {
2644 range: 0..4,
2645 kind: MarkKind::Bold
2646 }]
2647 );
2648 }
2649
2650 #[test]
2651 fn lines_round_trip_through_json_with_formatting() {
2652 let mut draft = Draft::plain("bold\nitem\nafter");
2653 draft.toggle(0..4, MarkKind::Bold);
2654 draft.set_line_kind(1, LineKind::Bullet(0), None, 0);
2655 let json = serde_json::to_string(&draft.to_lines()).unwrap();
2656 let lines: Vec<DraftLine> = serde_json::from_str(&json).unwrap();
2657 let restored = Draft::from_lines(&lines);
2658 assert_eq!(restored.text(), draft.text());
2659 assert_eq!(restored.to_html(), draft.to_html());
2660 assert_eq!(restored.lines(), draft.lines());
2661 }
2662
2663 fn typed_draft(text: &str) -> Draft {
2664 let mut draft = Draft::default();
2665 typed(&mut draft, text);
2666 draft
2667 }
2668
2669 fn mark(range: Range<usize>, kind: MarkKind) -> Mark {
2670 Mark { range, kind }
2671 }
2672
2673 #[test]
2674 fn typed_markdown_becomes_formatting() {
2675 let draft = typed_draft("a **bold** and *it* or _it_ ~~gone~~ `code`");
2676 assert_eq!(draft.text(), "a bold and it or it gone code");
2677 assert_eq!(
2678 draft.marks(),
2679 [
2680 mark(2..6, MarkKind::Bold),
2681 mark(11..13, MarkKind::Bold),
2682 mark(17..19, MarkKind::Italic),
2683 mark(20..24, MarkKind::Strike),
2684 mark(25..29, MarkKind::Code),
2685 ]
2686 );
2687 }
2688
2689 #[test]
2690 fn typed_link_keeps_the_label_and_carries_the_url() {
2691 let draft = typed_draft("see [docs](https://example.com)");
2692 assert_eq!(draft.text(), "see docs");
2693 assert_eq!(
2694 draft.marks(),
2695 [mark(4..8, MarkKind::Link("https://example.com".into()))]
2696 );
2697 }
2698
2699 fn typed_autolinked(draft: &mut Draft, text: &str) {
2700 for character in text.chars() {
2701 let mut next = draft.text().to_owned();
2702 next.push(character);
2703 let cursor = next.len();
2704 draft.apply_edit(&next, cursor, None);
2705 draft.autolink_typed(cursor);
2706 draft.take_edits();
2707 }
2708 }
2709
2710 fn autolinked(text: &str) -> Draft {
2711 let mut draft = Draft::default();
2712 typed_autolinked(&mut draft, text);
2713 draft
2714 }
2715
2716 fn edited(draft: &mut Draft, range: Range<usize>, replacement: &str) {
2717 let mut next = draft.text().to_owned();
2718 next.replace_range(range.clone(), replacement);
2719 draft.apply_edit(&next, range.start + replacement.len(), None);
2720 }
2721
2722 #[test]
2723 fn typed_url_followed_by_a_space_becomes_a_link() {
2724 let draft = autolinked("https://example.com ");
2725 assert_eq!(
2726 draft.marks(),
2727 [mark(0..19, MarkKind::Link("https://example.com".into()))]
2728 );
2729 }
2730
2731 #[test]
2732 fn typed_url_followed_by_a_newline_becomes_a_link() {
2733 let draft = autolinked("a mailto:x@y.de\n");
2734 assert_eq!(
2735 draft.marks(),
2736 [mark(2..15, MarkKind::Link("mailto:x@y.de".into()))]
2737 );
2738 }
2739
2740 #[test]
2741 fn autolink_leaves_trailing_punctuation_out_and_adds_the_scheme() {
2742 let draft = autolinked("see www.x.de. ");
2743 assert_eq!(
2744 draft.marks(),
2745 [mark(4..12, MarkKind::Link("https://www.x.de".into()))]
2746 );
2747 let wiki = autolinked("https://a.b/x_(y) ");
2748 assert_eq!(
2749 wiki.marks(),
2750 [mark(0..17, MarkKind::Link("https://a.b/x_(y)".into()))]
2751 );
2752 let bracketed = autolinked("https://a.b) ");
2753 assert_eq!(
2754 bracketed.marks(),
2755 [mark(0..11, MarkKind::Link("https://a.b".into()))]
2756 );
2757 }
2758
2759 #[test]
2760 fn autolink_starts_after_any_non_alphanumeric_character() {
2761 let bracketed = autolinked("(https://a.b) ");
2762 assert_eq!(
2763 bracketed.marks(),
2764 [mark(1..12, MarkKind::Link("https://a.b".into()))]
2765 );
2766 let quoted = autolinked("\"www.x.de\" ");
2767 assert_eq!(
2768 quoted.marks(),
2769 [mark(1..9, MarkKind::Link("https://www.x.de".into()))]
2770 );
2771 let colon = autolinked("see:https://a.b ");
2772 assert_eq!(
2773 colon.marks(),
2774 [mark(4..15, MarkKind::Link("https://a.b".into()))]
2775 );
2776 assert!(autolinked("xhttps://a.b ").marks().is_empty());
2777 }
2778
2779 #[test]
2780 fn a_link_labelled_with_a_bare_domain_keeps_its_url_when_relabelled() {
2781 let mut draft = Draft::plain("example.com");
2782 draft.set_link(0..11, "example.com");
2783 edited(&mut draft, 0..11, "our site");
2784 assert_eq!(
2785 draft.marks(),
2786 [mark(0..8, MarkKind::Link("https://example.com".into()))]
2787 );
2788 }
2789
2790 #[test]
2791 fn autolink_skips_plain_words_code_and_existing_links() {
2792 assert!(autolinked("example.com ").marks().is_empty());
2793 assert!(autolinked("http:// ").marks().is_empty());
2794 let mut block = Draft::from_markdown("```\nhttps://a.b");
2795 typed_autolinked(&mut block, " ");
2796 assert!(block.marks().is_empty());
2797 let mut code = Draft::plain("https://a.b");
2798 code.toggle(0..11, MarkKind::Code);
2799 typed_autolinked(&mut code, " ");
2800 assert_eq!(code.marks(), [mark(0..11, MarkKind::Code)]);
2801 let mut linked = Draft::plain("https://a.b");
2802 linked.set_link(0..11, "https://other.de");
2803 typed_autolinked(&mut linked, " ");
2804 assert_eq!(
2805 linked.marks(),
2806 [mark(0..11, MarkKind::Link("https://other.de".into()))]
2807 );
2808 }
2809
2810 #[test]
2811 fn markdown_import_links_bare_urls_outside_code_and_labels() {
2812 let draft = Draft::from_markdown("go to https://a.b now");
2813 assert_eq!(
2814 draft.marks(),
2815 [mark(6..17, MarkKind::Link("https://a.b".into()))]
2816 );
2817 assert_eq!(
2818 Draft::from_markdown("run `https://a.b` now").marks(),
2819 [mark(4..15, MarkKind::Code)]
2820 );
2821 let labelled = Draft::from_markdown("[https://a.b](https://c.d)");
2822 assert_eq!(
2823 labelled.marks(),
2824 [mark(0..11, MarkKind::Link("https://c.d".into()))]
2825 );
2826 assert!(has_markdown("x https://a.b y"));
2827 }
2828
2829 #[test]
2830 fn editing_an_auto_link_moves_its_url() {
2831 let mut draft = autolinked("https://a.bc ");
2832 edited(&mut draft, 11..12, "d");
2833 assert_eq!(
2834 draft.marks(),
2835 [mark(0..12, MarkKind::Link("https://a.bd".into()))]
2836 );
2837 edited(&mut draft, 11..11, "e");
2838 assert_eq!(
2839 draft.marks(),
2840 [mark(0..13, MarkKind::Link("https://a.bed".into()))]
2841 );
2842 }
2843
2844 #[test]
2845 fn editing_a_labelled_link_keeps_its_url() {
2846 let mut draft = typed_draft("[docs](https://example.com)");
2847 edited(&mut draft, 2..2, "x");
2848 assert_eq!(
2849 draft.marks(),
2850 [mark(0..5, MarkKind::Link("https://example.com".into()))]
2851 );
2852 }
2853
2854 #[test]
2855 fn breaking_an_auto_link_into_non_url_text_removes_it() {
2856 let mut draft = autolinked("https://a.bc ");
2857 edited(&mut draft, 9..9, " ");
2858 assert!(draft.marks().is_empty());
2859 }
2860
2861 #[test]
2862 fn an_auto_link_can_be_relabelled_or_unlinked() {
2863 let mut draft = autolinked("https://a.bc ");
2864 assert_eq!(draft.link_in(0..4), Some("https://a.bc".into()));
2865 draft.set_link(0..12, "https://other.de");
2866 assert_eq!(
2867 draft.marks(),
2868 [mark(0..12, MarkKind::Link("https://other.de".into()))]
2869 );
2870 edited(&mut draft, 12..12, "x");
2871 draft.set_link(0..12, "");
2872 assert!(draft.marks().is_empty());
2873 }
2874
2875 #[test]
2876 fn snake_case_and_spaced_stars_stay_text() {
2877 assert_eq!(typed_draft("snake_case_name").text(), "snake_case_name");
2878 assert_eq!(typed_draft("2 * 3 * 4").text(), "2 * 3 * 4");
2879 assert!(typed_draft("a** b**").marks().is_empty());
2880 }
2881
2882 #[test]
2883 fn typing_at_the_end_of_bold_continues_it_but_not_after_a_link() {
2884 let mut draft = Draft::plain("b");
2885 draft.toggle(0..1, MarkKind::Bold);
2886 typed(&mut draft, "x");
2887 assert_eq!(draft.marks(), [mark(0..2, MarkKind::Bold)]);
2888 let converted = typed_draft("**b**x");
2889 assert_eq!(converted.marks(), [mark(0..1, MarkKind::Bold)]);
2890 let mut linked = typed_draft("[a](u)");
2891 typed(&mut linked, "b");
2892 assert_eq!(
2893 linked.marks(),
2894 [mark(0..1, MarkKind::Link("https://u".into()))]
2895 );
2896 }
2897
2898 #[test]
2899 fn typing_style_switches_bold_on_and_off_for_the_next_text() {
2900 let mut draft = Draft::plain("ab");
2901 let typing = TypingStyle {
2902 at: 2,
2903 add: vec![MarkKind::Bold],
2904 remove: Vec::new(),
2905 };
2906 draft.apply_edit("abc", 3, Some(&typing));
2907 assert_eq!(draft.marks(), [mark(2..3, MarkKind::Bold)]);
2908 let off = TypingStyle {
2909 at: 3,
2910 add: Vec::new(),
2911 remove: vec![MarkKind::Bold],
2912 };
2913 draft.apply_edit("abcd", 4, Some(&off));
2914 assert_eq!(draft.marks(), [mark(2..3, MarkKind::Bold)]);
2915 }
2916
2917 #[test]
2918 fn toggle_on_a_mixed_selection_formats_all_then_clears() {
2919 let mut draft = Draft::plain("hello world");
2920 draft.toggle(0..5, MarkKind::Bold);
2921 assert_eq!(draft.state(0..11, &MarkKind::Bold), FormatState::Mixed);
2922 draft.toggle(0..11, MarkKind::Bold);
2923 assert_eq!(draft.state(0..11, &MarkKind::Bold), FormatState::On);
2924 draft.toggle(0..11, MarkKind::Bold);
2925 assert_eq!(draft.state(0..11, &MarkKind::Bold), FormatState::Off);
2926 assert!(draft.marks().is_empty());
2927 }
2928
2929 #[test]
2930 fn deleting_inside_and_across_marks_shifts_and_clips() {
2931 let mut draft = Draft::plain("aa bold cc");
2932 draft.toggle(3..7, MarkKind::Bold);
2933 draft.apply_edit("aa bld cc", 4, None);
2934 assert_eq!(draft.marks(), [mark(3..6, MarkKind::Bold)]);
2935 draft.apply_edit("ald cc", 1, None);
2936 assert_eq!(draft.marks(), [mark(1..3, MarkKind::Bold)]);
2937 draft.apply_edit("XXald cc", 2, None);
2938 assert_eq!(draft.marks(), [mark(3..5, MarkKind::Bold)]);
2939 }
2940
2941 #[test]
2942 fn repeated_characters_are_attributed_to_the_cursor() {
2943 let mut draft = Draft::plain("aa");
2944 draft.toggle(0..1, MarkKind::Bold);
2945 draft.apply_edit("aaa", 2, None);
2946 assert_eq!(draft.marks(), [mark(0..2, MarkKind::Bold)]);
2947 }
2948
2949 #[test]
2950 fn list_shortcuts_turn_lines_into_items() {
2951 let draft = typed_draft("- one");
2952 assert_eq!(draft.text(), "• one");
2953 assert_eq!(draft.lines(), [LineKind::Bullet(0)]);
2954 let numbered = typed_draft("1. one");
2955 assert_eq!(numbered.text(), "1. one");
2956 assert_eq!(numbered.lines(), [LineKind::Numbered(0)]);
2957 let quote = typed_draft(">said");
2958 assert_eq!(quote.text(), "said");
2959 assert_eq!(quote.lines(), [LineKind::Quote]);
2960 let spaced = typed_draft("> said");
2961 assert_eq!(spaced.text(), " said");
2962 assert_eq!(spaced.lines(), [LineKind::Quote]);
2963 }
2964
2965 #[test]
2966 fn enter_continues_a_list_and_ends_it_on_an_empty_item() {
2967 let mut draft = typed_draft("1. one");
2968 let cursor = draft.break_line(draft.text().len(), false).unwrap();
2969 assert_eq!(draft.text(), "1. one\n2. ");
2970 assert_eq!(cursor, draft.text().len());
2971 typed(&mut draft, "two");
2972 let cursor = draft.break_line(draft.text().len(), false).unwrap();
2973 let cursor = draft.break_line(cursor, false).unwrap();
2974 assert_eq!(draft.text(), "1. one\n2. two\n");
2975 assert_eq!(cursor, draft.text().len());
2976 assert_eq!(draft.lines()[2], LineKind::Text);
2977 assert_eq!(Draft::plain("x").break_line(1, false), None);
2978 }
2979
2980 #[test]
2981 fn enter_in_the_middle_of_an_item_splits_it_and_renumbers() {
2982 let mut draft = Draft::from_markdown("1. ab\n2. c");
2983 draft.break_line(4, false).unwrap();
2984 assert_eq!(draft.text(), "1. a\n2. b\n3. c");
2985 let edits = draft.take_edits();
2986 assert_eq!(map_offset(&edits, 4), 8);
2987 }
2988
2989 #[test]
2990 fn tab_nests_and_shift_tab_lifts_list_items() {
2991 let mut draft = Draft::from_markdown("- a\n- b");
2992 assert!(draft.indent(6..6, false));
2993 assert_eq!(draft.lines(), [LineKind::Bullet(0), LineKind::Bullet(1)]);
2994 assert_eq!(draft.text(), "• a\n◦ b");
2995 assert!(draft.indent(draft.text().len()..draft.text().len(), true));
2996 assert!(draft.indent(draft.text().len()..draft.text().len(), true));
2997 assert_eq!(draft.text(), "• a\nb");
2998 assert!(!Draft::plain("x").indent(0..0, false));
2999 }
3000
3001 #[test]
3002 fn nested_numbering_counts_per_level() {
3003 let draft = Draft::from_markdown("1. a\n 1. x\n 2. y\n2. b");
3004 assert_eq!(draft.text(), "1. a\n1. x\n2. y\n2. b");
3005 }
3006
3007 #[test]
3008 fn backspace_at_an_item_start_drops_the_bullet() {
3009 let mut draft = Draft::from_markdown("- a");
3010 let cursor = draft.backspace_at_start(bullet_marker(0).len()).unwrap();
3011 assert_eq!((draft.text(), cursor), ("a", 0));
3012 assert_eq!(draft.lines(), [LineKind::Text]);
3013 }
3014
3015 #[test]
3016 fn typing_before_a_bullet_lands_after_it() {
3017 let mut draft = Draft::from_markdown("- a");
3018 let marker = bullet_marker(0);
3019 let cursor = draft.apply_edit(&format!("x{marker}a"), 1, None);
3020 assert_eq!(draft.text(), format!("{marker}xa"));
3021 assert_eq!(cursor, marker.len() + 1);
3022 assert_eq!(
3023 draft.take_edits(),
3024 [
3025 (0..1, String::new()),
3026 (marker.len() + 1..marker.len() + 1, "x".to_owned())
3027 ]
3028 );
3029 }
3030
3031 #[test]
3032 fn a_damaged_marker_turns_the_line_into_text() {
3033 let mut draft = Draft::from_markdown("- a");
3034 draft.apply_edit("•a", 1, None);
3035 assert_eq!(draft.lines(), [LineKind::Text]);
3036 }
3037
3038 #[test]
3039 fn fence_and_enter_open_a_code_block_that_enter_continues() {
3040 let mut draft = typed_draft("```rust");
3041 let cursor = draft.break_line(draft.text().len(), false).unwrap();
3042 assert_eq!((draft.text(), cursor), ("", 0));
3043 assert_eq!(draft.lines(), [LineKind::Code(Some("rust".into()))]);
3044 typed(&mut draft, "fn x() {}");
3045 let cursor = draft.break_line(draft.text().len(), false).unwrap();
3046 assert_eq!(draft.lines().len(), 2);
3047 assert_eq!(draft.break_line(cursor, false), Some(cursor));
3048 assert_eq!(draft.lines()[1], LineKind::Text);
3049 assert_eq!(
3050 draft.to_html(),
3051 "<pre class=\"language-rust skipProofing\" spellcheck=\"false\"><code>fn x() {}</code></pre>"
3052 );
3053 }
3054
3055 #[test]
3056 fn markdown_inside_code_stays_literal() {
3057 let mut draft = typed_draft("```");
3058 let cursor = draft.break_line(3, false).unwrap();
3059 assert_eq!(cursor, 0);
3060 typed(&mut draft, "a **b**");
3061 assert_eq!(draft.text(), "a **b**");
3062 assert!(draft.marks().is_empty());
3063 }
3064
3065 #[test]
3066 fn html_nests_overlapping_marks_and_escapes() {
3067 let mut draft = Draft::plain("a<b & c");
3068 draft.toggle(0..4, MarkKind::Bold);
3069 draft.toggle(2..7, MarkKind::Italic);
3070 assert_eq!(draft.to_html(), "<b>a&lt;<i>b </i></b><i>&amp; c</i>");
3071 }
3072
3073 fn long_url(length: usize) -> String {
3074 let head = "https://portal.example/#@contoso/blade/";
3075 format!("{head}{}", "a".repeat(length - head.len()))
3076 }
3077
3078 #[test]
3079 fn html_shortens_a_long_link_that_shows_its_own_url() {
3080 let url = long_url(140);
3081 let draft = Draft::from_markdown(&format!("see {url} now"));
3082 assert_eq!(
3083 draft.to_html(),
3084 format!(
3085 "see <a href=\"{url}\" title=\"{url}\">{}…</a> now",
3086 &url[..99]
3087 )
3088 );
3089 let www = format!("www.{}", &url["https://".len()..]);
3090 let draft = Draft::from_markdown(&www);
3091 assert_eq!(
3092 draft.to_html(),
3093 format!(
3094 "<a href=\"https://{www}\" title=\"https://{www}\">{}…</a>",
3095 &www[..99]
3096 )
3097 );
3098 }
3099
3100 #[test]
3101 fn html_keeps_short_links_and_labels_whole() {
3102 let exact = long_url(100);
3103 assert_eq!(
3104 Draft::from_markdown(&exact).to_html(),
3105 format!("<a href=\"{exact}\">{exact}</a>")
3106 );
3107 let label = "l".repeat(120);
3108 let url = long_url(140);
3109 assert_eq!(
3110 Draft::from_markdown(&format!("[{label}]({url})")).to_html(),
3111 format!("<a href=\"{url}\">{label}</a>")
3112 );
3113 }
3114
3115 #[test]
3116 fn html_shortening_moves_the_marks_after_the_link() {
3117 let url = long_url(130);
3118 let mut draft = Draft::from_markdown(&format!("{url} tail"));
3119 let length = draft.text().len();
3120 draft.toggle(90..length, MarkKind::Bold);
3121 draft.toggle(120..125, MarkKind::Italic);
3122 assert_eq!(
3123 draft.to_html(),
3124 format!(
3125 "<a href=\"{url}\" title=\"{url}\">{}<b>{}…</b></a><b> tail</b>",
3126 &url[..90],
3127 &url[90..99]
3128 )
3129 );
3130 }
3131
3132 #[test]
3133 fn html_covers_every_format() {
3134 let draft = Draft::from_markdown(
3135 "**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```",
3136 );
3137 let mut underlined = draft.clone();
3138 underlined.toggle(0..1, MarkKind::Underline);
3139 assert_eq!(
3140 underlined.to_html(),
3141 "<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>\
3142 <blockquote>q1<br>q2</blockquote>\
3143 <ul><li>a<ul><li>b</li></ul></li></ul>\
3144 <ol><li>x</li><li>y</li></ol>\
3145 <pre class=\"language-py skipProofing\" spellcheck=\"false\"><code>print(1)</code></pre>"
3146 );
3147 }
3148
3149 #[test]
3150 fn script_and_size_marks_export_teams_html() {
3151 let mut draft = Draft::plain("x2 H2O big tiny");
3152 draft.toggle(1..2, MarkKind::Superscript);
3153 draft.toggle(4..5, MarkKind::Subscript);
3154 draft.set_size(7..10, Some(SizeStep::Large));
3155 draft.set_size(11..15, Some(SizeStep::Small));
3156 assert_eq!(
3157 draft.to_html(),
3158 "x<sup>2</sup> H<sub>2</sub>O <span style=\"font-size:x-large;\">big</span> \
3159 <span style=\"font-size:xx-small;\">tiny</span>"
3160 );
3161 }
3162
3163 #[test]
3164 fn script_and_size_marks_round_trip_through_html() {
3165 let mut source = Draft::plain("x2 H2O big tiny");
3166 source.toggle(1..2, MarkKind::Superscript);
3167 source.toggle(4..5, MarkKind::Subscript);
3168 source.toggle(7..10, MarkKind::Bold);
3169 source.set_size(7..10, Some(SizeStep::Large));
3170 source.set_size(11..15, Some(SizeStep::Small));
3171 let back = Draft::from_spans(&html_to_spans(&source.to_html()));
3172 assert_eq!(back.text(), source.text());
3173 assert_eq!(back.marks(), source.marks());
3174 }
3175
3176 #[test]
3177 fn inherit_and_pixel_sizes_import_without_a_size_mark() {
3178 let spans = html_to_spans(
3179 "<span style=\"font-size:inherit;\">a</span><span style=\"font-size:14px\">b</span>",
3180 );
3181 assert!(Draft::from_spans(&spans).marks().is_empty());
3182 }
3183
3184 #[test]
3185 fn superscript_and_subscript_exclude_each_other() {
3186 let mut draft = Draft::plain("abcdef");
3187 draft.toggle(0..4, MarkKind::Superscript);
3188 draft.toggle(2..6, MarkKind::Subscript);
3189 assert_eq!(
3190 draft.marks(),
3191 [
3192 mark(0..2, MarkKind::Superscript),
3193 mark(2..6, MarkKind::Subscript)
3194 ]
3195 );
3196 }
3197
3198 #[test]
3199 fn typing_style_switches_between_script_marks() {
3200 let mut style = TypingStyle::default();
3201 style.toggle(MarkKind::Subscript, &[MarkKind::Superscript]);
3202 assert_eq!(
3203 style.apply(vec![MarkKind::Superscript]),
3204 vec![MarkKind::Subscript]
3205 );
3206 }
3207
3208 #[test]
3209 fn size_changes_on_a_partial_range_split_the_mark() {
3210 let mut draft = Draft::plain("abcdef");
3211 draft.set_size(0..6, Some(SizeStep::Large));
3212 draft.set_size(2..4, Some(SizeStep::Small));
3213 assert_eq!(
3214 draft.marks(),
3215 [
3216 mark(2..4, MarkKind::Size(SizeStep::Small)),
3217 mark(0..2, MarkKind::Size(SizeStep::Large)),
3218 mark(4..6, MarkKind::Size(SizeStep::Large)),
3219 ]
3220 );
3221 assert_eq!(draft.size_in(2..4), Some(SizeStep::Small));
3222 assert_eq!(draft.size_in(0..6), None);
3223 draft.set_size(0..6, None);
3224 assert!(draft.marks().is_empty());
3225 }
3226
3227 #[test]
3228 fn ordered_lists_keep_their_start() {
3229 let draft = Draft::from_markdown("3. c\n4. d");
3230 assert_eq!(draft.to_html(), "<ol start=\"3\"><li>c</li><li>d</li></ol>");
3231 }
3232
3233 #[test]
3234 fn spans_round_trip_through_html() {
3235 let source = Draft::from_markdown(
3236 "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",
3237 );
3238 let back = Draft::from_spans(&html_to_spans(&source.to_html()));
3239 assert_eq!(back.text(), source.text());
3240 assert_eq!(back.lines(), source.lines());
3241 assert_eq!(back.marks(), source.marks());
3242 }
3243
3244 #[test]
3245 fn mentions_from_html_come_back_as_at_text() {
3246 let draft = Draft::from_spans(&html_to_spans("hi <at id=\"0\">Ada</at> <b>now</b>"));
3247 assert_eq!(draft.text(), "hi @Ada now");
3248 assert_eq!(draft.marks(), [mark(8..11, MarkKind::Bold)]);
3249 }
3250
3251 #[test]
3252 fn pasted_markdown_is_detected() {
3253 assert!(has_markdown("see **this**"));
3254 assert!(has_markdown("- a\n- b"));
3255 assert!(has_markdown("```\nx\n```"));
3256 assert!(!has_markdown("plain text, 2*3=6 and snake_case"));
3257 }
3258
3259 #[test]
3260 fn slices_carry_formatting_into_another_draft() {
3261 let source = Draft::from_markdown("intro **bold**\n- one\n- two");
3262 let end = source.text().len();
3263 let fragment = source.slice(6..end);
3264 assert_eq!(fragment[0].kind, LineKind::Text);
3265 assert_eq!(fragment[1].kind, LineKind::Bullet(0));
3266 let mut target = Draft::plain("x ");
3267 let cursor = target.insert_lines(2..2, &fragment);
3268 assert_eq!(target.text(), "x bold\n• one\n• two");
3269 assert_eq!(cursor, target.text().len());
3270 assert_eq!(target.marks(), [mark(2..6, MarkKind::Bold)]);
3271 assert_eq!(
3272 target.lines()[1..],
3273 [LineKind::Bullet(0), LineKind::Bullet(0)]
3274 );
3275 }
3276
3277 #[test]
3278 fn markdown_pasted_on_its_own_line_converts_from_the_first_line() {
3279 let raw = "- a\n- b";
3280 let mut draft = Draft::plain("");
3281 draft.apply_edit(raw, raw.len(), None);
3282 let lines = Draft::from_markdown(raw).slice(0..usize::MAX);
3283 let cursor = draft.insert_lines(0..raw.len(), &lines);
3284 assert_eq!(draft.text(), "• a\n• b");
3285 assert_eq!(cursor, draft.text().len());
3286 let mut inline = Draft::plain("x ");
3287 inline.apply_edit("x **b**", 7, None);
3288 let lines = Draft::from_markdown("**b**").slice(0..usize::MAX);
3289 inline.insert_lines(2..7, &lines);
3290 assert_eq!(inline.text(), "x b");
3291 assert_eq!(inline.marks(), [mark(2..3, MarkKind::Bold)]);
3292 }
3293
3294 #[test]
3295 fn a_paste_inside_a_line_puts_the_cursor_after_the_pasted_text() {
3296 let lines = Draft::from_markdown("**big**").slice(0..usize::MAX);
3297 let mut plain = Draft::plain("hello world");
3298 assert_eq!(plain.insert_lines(6..6, &lines), 9);
3299 assert_eq!(plain.text(), "hello bigworld");
3300 let mut item = Draft::from_markdown("- item one");
3301 let before_one = bullet_marker(0).len() + "item ".len();
3302 assert_eq!(
3303 item.insert_lines(before_one..before_one, &lines),
3304 before_one + 3
3305 );
3306 }
3307
3308 #[test]
3309 fn a_selection_ending_at_the_next_line_start_leaves_that_line_alone() {
3310 let mut draft = Draft::plain("first\nsecond");
3311 assert_eq!(
3312 draft.line_state(0..6, &LineKind::Bullet(0)),
3313 FormatState::Off
3314 );
3315 draft.toggle_lines(0..6, LineKind::Bullet(0));
3316 assert_eq!(draft.lines(), [LineKind::Bullet(0), LineKind::Text]);
3317 let end_of_first = draft.line_ranges()[1].start;
3318 assert_eq!(
3319 draft.line_state(0..end_of_first, &LineKind::Bullet(0)),
3320 FormatState::On
3321 );
3322 assert!(draft.indent(0..end_of_first, false));
3323 assert_eq!(draft.lines()[1], LineKind::Text);
3324 }
3325
3326 #[test]
3327 fn links_only_take_http_https_and_mailto() {
3328 assert_eq!(link_url("example.com"), Some("https://example.com".into()));
3329 assert_eq!(link_url("mailto:a@b.test"), Some("mailto:a@b.test".into()));
3330 assert_eq!(link_url("javascript:alert(1)"), None);
3331 assert_eq!(link_url("data:text/html,x"), None);
3332 let typed = typed_draft("[x](javascript:alert)");
3333 assert!(typed.marks().is_empty());
3334 let pasted = Draft::from_markdown("[x](javascript:alert) [y](example.com)");
3335 assert_eq!(
3336 pasted.marks(),
3337 [mark(22..23, MarkKind::Link("https://example.com".into()))]
3338 );
3339 let mut set = Draft::plain("go");
3340 set.set_link(0..2, "javascript:alert(1)");
3341 assert!(set.marks().is_empty());
3342 let spans = Draft::from_spans(&html_to_spans("<a href=\"javascript:x\">bad</a>"));
3343 assert!(spans.marks().is_empty());
3344 }
3345
3346 #[test]
3347 fn code_lines_hold_only_their_content() {
3348 let mut draft = Draft::from_markdown("```\nlet a = 1;\n\u{2003}b\n```");
3349 assert_eq!(draft.text(), "let a = 1;\n\u{2003}b");
3350 assert_eq!(
3351 draft.to_html(),
3352 "<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>let a = 1;<br>\u{2003}b</code></pre>"
3353 );
3354 assert_eq!(draft.backspace_at_start(draft.line_ranges()[1].start), None);
3355 assert_eq!(draft.backspace_at_start(0), Some(0));
3356 assert_eq!(draft.lines()[0], LineKind::Text);
3357 }
3358
3359 #[test]
3360 fn in_code_covers_code_lines_and_the_inside_of_inline_code() {
3361 let draft = Draft::from_markdown("a `cd` e\n```\nx\n```");
3362 assert!(!draft.in_code(2));
3363 assert!(draft.in_code(3));
3364 assert!(!draft.in_code(4));
3365 assert!(draft.in_code(draft.text().len()));
3366 }
3367
3368 #[test]
3369 fn code_indentation_is_kept_on_paste_split_and_send() {
3370 let mut draft = typed_draft("```py");
3371 let cursor = draft.break_line(draft.text().len(), false).unwrap();
3372 let pasted = "def f():\n return 1";
3373 let mut next = draft.text().to_owned();
3374 next.insert_str(cursor, pasted);
3375 draft.apply_edit(&next, cursor + pasted.len(), None);
3376 assert_eq!(
3377 draft.to_html(),
3378 "<pre class=\"language-py skipProofing\" spellcheck=\"false\"><code>def f():<br> return 1</code></pre>"
3379 );
3380 let mut split = Draft::from_markdown("```\n a b\n```");
3381 let after_a = " a".len();
3382 split.break_line(after_a, false).unwrap();
3383 assert_eq!(
3384 split.to_html(),
3385 "<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code> a<br> b</code></pre>"
3386 );
3387 }
3388
3389 #[test]
3390 fn delete_at_a_line_end_joins_the_next_item_without_its_bullet() {
3391 let mut draft = Draft::from_markdown("- a\n- b");
3392 let end_of_first = draft.line_ranges()[0].end;
3393 assert_eq!(draft.delete_forward(end_of_first), Some(end_of_first));
3394 assert_eq!(draft.text(), "• ab");
3395 assert_eq!(draft.delete_forward(0), Some(bullet_marker(0).len()));
3396 assert_eq!(draft.text(), "• b");
3397 assert_eq!(Draft::plain("a\nb").delete_forward(1), None);
3398 }
3399
3400 #[test]
3401 fn host_and_port_links_are_schemeless() {
3402 assert_eq!(
3403 link_url("localhost:3000"),
3404 Some("https://localhost:3000".into())
3405 );
3406 assert_eq!(
3407 link_url("example.com:8080/x"),
3408 Some("https://example.com:8080/x".into())
3409 );
3410 assert_eq!(link_url("javascript:alert(1)"), None);
3411 assert_eq!(link_url("tel:0123456"), None);
3412 }
3413
3414 #[test]
3415 fn a_quote_stays_a_quote_when_split_or_joined() {
3416 let mut draft = Draft::from_markdown("> a\n> b");
3417 let second = draft.line_ranges()[1].start;
3418 assert_eq!(draft.break_line(second, true), Some(second + 1));
3419 assert_eq!(
3420 draft.lines(),
3421 [LineKind::Quote, LineKind::Quote, LineKind::Quote]
3422 );
3423 let mut joined = Draft::from_markdown("> a\n> b");
3424 let second = joined.line_ranges()[1].start;
3425 assert_eq!(joined.backspace_at_start(second), Some(second - 1));
3426 assert_eq!(
3427 (joined.text(), joined.lines()),
3428 ("ab", &[LineKind::Quote][..])
3429 );
3430 assert_eq!(joined.backspace_at_start(0), Some(0));
3431 assert_eq!(joined.lines(), [LineKind::Text]);
3432 }
3433
3434 #[test]
3435 fn journal_merges_edits_into_ranges_of_the_old_text() {
3436 let mut draft = Draft::plain("a **b** c");
3437 draft.splice(5..7, "", &[]);
3438 draft.splice(2..4, "", &[]);
3439 draft.splice(0..0, "X", &[]);
3440 let edits = draft.take_edits();
3441 assert_eq!(
3442 edits,
3443 [
3444 (0..0, "X".to_owned()),
3445 (2..4, String::new()),
3446 (5..7, String::new())
3447 ]
3448 );
3449 assert_eq!(
3450 reverse_edits(&edits, "a **b** c")[1],
3451 (3..3, "**".to_owned())
3452 );
3453 let mut touching = Draft::plain("abc");
3454 touching.splice(1..2, "XY", &[]);
3455 touching.splice(3..3, "Z", &[]);
3456 assert_eq!(touching.take_edits(), [(1..2, "XYZ".to_owned())]);
3457 }
3458
3459 #[test]
3460 fn trimming_drops_blank_lines_and_outer_spaces() {
3461 let mut draft = Draft::plain("\n hi **x** \n\n");
3462 draft.toggle(6..11, MarkKind::Bold);
3463 let trimmed = draft.trimmed();
3464 assert_eq!(trimmed.text(), "hi **x**");
3465 assert_eq!(trimmed.marks(), [mark(3..8, MarkKind::Bold)]);
3466 }
3467
3468 #[test]
3469 fn toolbar_line_toggles_apply_to_every_selected_line() {
3470 let mut draft = Draft::plain("a\nb");
3471 draft.toggle_lines(0..3, LineKind::Numbered(0));
3472 assert_eq!(draft.text(), "1. a\n2. b");
3473 assert_eq!(
3474 draft.line_state(0..4, &LineKind::Numbered(0)),
3475 FormatState::On
3476 );
3477 draft.toggle_lines(0..9, LineKind::Bullet(0));
3478 assert_eq!(draft.text(), "• a\n• b");
3479 let end = draft.text().len();
3480 draft.toggle_lines(0..end, LineKind::Bullet(0));
3481 assert_eq!(draft.text(), "a\nb");
3482 }
3483
3484 #[test]
3485 fn links_are_set_replaced_and_removed() {
3486 let mut draft = Draft::plain("go here");
3487 draft.set_link(3..7, "https://a.test");
3488 assert_eq!(draft.link_in(4..4), Some("https://a.test".into()));
3489 draft.set_link(3..7, "");
3490 assert!(draft.marks().is_empty());
3491 let end = draft.insert_link(7, " https://b.test", "https://b.test");
3492 assert_eq!(end, draft.text().len());
3493 }
3494}