BlueGit

ict rusty-teams

Files

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

draft.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
draft.rs 122.3 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
2055fn inline_html(content: &str, marks: &[Mark]) -> String {
2056 let mut boundaries: Vec<usize> = marks
2057 .iter()
2058 .flat_map(|mark| [mark.range.start, mark.range.end])
2059 .chain([0, content.len()])
2060 .filter(|offset| *offset <= content.len())
2061 .collect();
2062 boundaries.sort_unstable();
2063 boundaries.dedup();
2064 let mut html = String::new();
2065 let mut open: Vec<&MarkKind> = Vec::new();
2066 for window in boundaries.windows(2) {
2067 let segment = window[0]..window[1];
2068 let mut active: Vec<&MarkKind> = marks
2069 .iter()
2070 .filter(|mark| mark.range.start <= segment.start && segment.end <= mark.range.end)
2071 .map(|mark| &mark.kind)
2072 .collect();
2073 active.sort();
2074 active.dedup();
2075 let common = open
2076 .iter()
2077 .zip(active.iter())
2078 .take_while(|(left, right)| left == right)
2079 .count();
2080 for kind in open.drain(common..).rev() {
2081 html.push_str(kind.close_tag());
2082 }
2083 for kind in &active[common..] {
2084 html.push_str(&kind.open_tag());
2085 }
2086 open.extend(active[common..].iter().copied());
2087 html.push_str(&escape_html(&content[segment]));
2088 }
2089 for kind in open.into_iter().rev() {
2090 html.push_str(kind.close_tag());
2091 }
2092 html
2093}
2094
2095fn list_html(lines: &[DraftLine]) -> String {
2096 let close = |ordered: bool| if ordered { "</li></ol>" } else { "</li></ul>" };
2097 let mut html = String::new();
2098 let mut open: Vec<(u8, bool)> = Vec::new();
2099 for line in lines {
2100 let ordered = matches!(line.kind, LineKind::Numbered(_));
2101 let depth = line
2102 .kind
2103 .depth()
2104 .min(open.last().map_or(0, |(depth, _)| depth + 1));
2105 while open
2106 .last()
2107 .is_some_and(|(open_depth, _)| *open_depth > depth)
2108 {
2109 let (_, was_ordered) = open.pop().unwrap_or_default();
2110 html.push_str(close(was_ordered));
2111 }
2112 match open.last().copied() {
2113 Some((open_depth, open_ordered)) if open_depth == depth && open_ordered == ordered => {
2114 html.push_str("</li>");
2115 }
2116 Some((open_depth, open_ordered)) if open_depth == depth => {
2117 html.push_str(close(open_ordered));
2118 open.pop();
2119 html.push_str(&list_open(ordered, line.number));
2120 open.push((depth, ordered));
2121 }
2122 _ => {
2123 html.push_str(&list_open(ordered, line.number));
2124 open.push((depth, ordered));
2125 }
2126 }
2127 html.push_str("<li>");
2128 html.push_str(&inline_html(&line.content, &line.marks));
2129 }
2130 for (_, ordered) in open.into_iter().rev() {
2131 html.push_str(close(ordered));
2132 }
2133 html
2134}
2135
2136fn list_open(ordered: bool, number: Option<u32>) -> String {
2137 match (ordered, number) {
2138 (false, _) => "<ul>".to_owned(),
2139 (true, Some(start)) if start != 1 => format!("<ol start=\"{start}\">"),
2140 (true, _) => "<ol>".to_owned(),
2141 }
2142}
2143
2144/// Text that `from_markdown` would format: pasting it converts.
2145pub fn has_markdown(text: &str) -> bool {
2146 let draft = Draft::from_markdown(text);
2147 !draft.marks.is_empty() || draft.lines.iter().any(|kind| *kind != LineKind::Text)
2148}
2149
2150fn markdown_lines(text: &str) -> Vec<DraftLine> {
2151 let sources: Vec<&str> = text
2152 .split('\n')
2153 .map(|raw| raw.strip_suffix('\r').unwrap_or(raw))
2154 .collect();
2155 let mut lines = Vec::new();
2156 let mut code: Option<Option<String>> = None;
2157 let mut position = 0;
2158 while position < sources.len() {
2159 let raw = sources[position];
2160 position += 1;
2161 let trimmed = raw.trim_start();
2162 if let Some(language) = &code {
2163 if trimmed.starts_with(FENCE) && trimmed.trim_end() == FENCE {
2164 code = None;
2165 } else {
2166 lines.push(DraftLine {
2167 kind: LineKind::Code(language.clone()),
2168 number: None,
2169 content: raw.to_owned(),
2170 marks: Vec::new(),
2171 });
2172 }
2173 continue;
2174 }
2175 if trimmed.starts_with(FENCE)
2176 && !trimmed[FENCE.len()..].contains('`')
2177 && let Some(language) = fence_language(trimmed)
2178 {
2179 code = Some(language);
2180 continue;
2181 }
2182 if let Some((rows, consumed)) = markdown_table(&sources[position - 1..]) {
2183 let rows = rows
2184 .into_iter()
2185 .map(|row| row.iter().map(|cell| parse_inline(cell).0).collect())
2186 .collect();
2187 lines.push(table_line(Table::from_rows(rows)));
2188 position += consumed - 1;
2189 continue;
2190 }
2191 let indent: usize = raw[..raw.len() - trimmed.len()]
2192 .chars()
2193 .map(|character| if character == '\t' { 4 } else { 1 })
2194 .sum();
2195 let depth = ((indent / MARKDOWN_INDENT) as u8).min(MAX_DEPTH);
2196 let (kind, number, content) = if let Some((level, rest)) = heading_prefix(trimmed) {
2197 (LineKind::Heading(level), None, rest)
2198 } else if let Some(rest) = PASTED_BULLETS
2199 .iter()
2200 .find_map(|bullet| trimmed.strip_prefix(bullet))
2201 {
2202 (LineKind::Bullet(depth), None, rest)
2203 } else if let Some((length, number)) = numbered_marker(trimmed) {
2204 (LineKind::Numbered(depth), Some(number), &trimmed[length..])
2205 } else if let Some(rest) = trimmed
2206 .strip_prefix("> ")
2207 .or_else(|| (trimmed == ">").then_some(""))
2208 {
2209 (LineKind::Quote, None, rest)
2210 } else {
2211 (LineKind::Text, None, raw)
2212 };
2213 let (content, marks) = parse_inline(content);
2214 lines.push(DraftLine {
2215 kind,
2216 number,
2217 content,
2218 marks,
2219 });
2220 }
2221 lines
2222}
2223
2224fn table_line(table: Table) -> DraftLine {
2225 DraftLine {
2226 kind: LineKind::Table(table),
2227 number: None,
2228 content: TABLE_MARK.to_string(),
2229 marks: Vec::new(),
2230 }
2231}
2232
2233/// `# ` to `###### `: the level, capped at the three Teams offers, and the rest of the line.
2234fn heading_prefix(line: &str) -> Option<(u8, &str)> {
2235 let hashes = line.bytes().take_while(|byte| *byte == b'#').count();
2236 let rest = line[hashes..].strip_prefix(' ')?;
2237 (1..=6)
2238 .contains(&hashes)
2239 .then(|| ((hashes as u8).min(MAX_HEADING), rest))
2240}
2241
2242fn parse_inline(source: &str) -> (String, Vec<Mark>) {
2243 let mut text = String::with_capacity(source.len());
2244 let mut marks = Vec::new();
2245 parse_into(source, &mut text, &mut marks, true);
2246 (text, marks)
2247}
2248
2249fn parse_into(source: &str, text: &mut String, marks: &mut Vec<Mark>, autolink: bool) {
2250 let mut rest = source;
2251 let mut previous: Option<char> = None;
2252 while let Some(character) = rest.chars().next() {
2253 if autolink
2254 && let Some(length) = bare_url_at(rest, previous)
2255 && let Some(url) = link_url(&rest[..length])
2256 {
2257 let start = text.len();
2258 text.push_str(&rest[..length]);
2259 marks.push(Mark {
2260 range: start..text.len(),
2261 kind: MarkKind::Link(url),
2262 });
2263 previous = rest[..length].chars().next_back();
2264 rest = &rest[length..];
2265 continue;
2266 }
2267 if let Some((inner, consumed, kind)) = inline_at(rest, previous) {
2268 let start = text.len();
2269 match kind {
2270 MarkKind::Code => text.push_str(inner),
2271 MarkKind::Link(_) => parse_into(inner, text, marks, false),
2272 _ => parse_into(inner, text, marks, autolink),
2273 }
2274 marks.push(Mark {
2275 range: start..text.len(),
2276 kind,
2277 });
2278 previous = rest[..consumed].chars().next_back();
2279 rest = &rest[consumed..];
2280 continue;
2281 }
2282 text.push(character);
2283 previous = Some(character);
2284 rest = &rest[character.len_utf8()..];
2285 }
2286}
2287
2288/// A format starting at the beginning of `rest`: its inner text, the bytes it spans, its kind.
2289fn inline_at(rest: &str, previous: Option<char>) -> Option<(&str, usize, MarkKind)> {
2290 if let Some(after) = rest.strip_prefix('`') {
2291 let end = after.find('`')?;
2292 let inner = &after[..end];
2293 return (!inner.trim().is_empty()).then_some((inner, end + 2, MarkKind::Code));
2294 }
2295 if rest.starts_with('[') {
2296 let captures = LINK_AT.captures(rest)?;
2297 let label = captures.get(1)?;
2298 return Some((
2299 label.as_str(),
2300 captures.get(0)?.end(),
2301 MarkKind::Link(link_url(&captures[2])?),
2302 ));
2303 }
2304 for (marker, kind) in [("**", MarkKind::Bold), ("~~", MarkKind::Strike)] {
2305 if let Some(after) = rest.strip_prefix(marker) {
2306 let end = after.find(marker)?;
2307 let inner = &after[..end];
2308 return valid_inner(inner).then_some((inner, end + 4, kind));
2309 }
2310 }
2311 for marker in ['*', '_'] {
2312 let Some(after) = rest.strip_prefix(marker) else {
2313 continue;
2314 };
2315 if previous.is_some_and(char::is_alphanumeric) || after.starts_with(marker) {
2316 return None;
2317 }
2318 let end = after.find(marker)?;
2319 let inner = &after[..end];
2320 let followed_by_word = after[end + 1..]
2321 .chars()
2322 .next()
2323 .is_some_and(char::is_alphanumeric);
2324 return (valid_inner(inner) && !followed_by_word).then_some((
2325 inner,
2326 end + 2,
2327 MarkKind::Italic,
2328 ));
2329 }
2330 None
2331}
2332
2333fn cell_text(spans: &[Span]) -> String {
2334 let mut builder = SpanLines::default();
2335 builder.walk(spans, &LineKind::Text, &[]);
2336 builder
2337 .finish()
2338 .into_iter()
2339 .map(|line| line.content)
2340 .collect::<Vec<_>>()
2341 .join("\n")
2342}
2343
2344#[derive(Default)]
2345struct SpanLines {
2346 lines: Vec<DraftLine>,
2347 open: bool,
2348}
2349
2350impl SpanLines {
2351 fn start_line(&mut self, kind: &LineKind, number: Option<u32>) {
2352 self.lines.push(DraftLine {
2353 kind: kind.clone(),
2354 number,
2355 content: String::new(),
2356 marks: Vec::new(),
2357 });
2358 self.open = true;
2359 }
2360
2361 fn append(&mut self, text: &str, kind: &LineKind, marks: &[MarkKind]) {
2362 for (index, piece) in text.split('\n').enumerate() {
2363 if index > 0 || !self.open {
2364 self.start_line(kind, None);
2365 }
2366 let Some(line) = self.lines.last_mut() else {
2367 continue;
2368 };
2369 let start = line.content.len();
2370 line.content.push_str(piece);
2371 let end = line.content.len();
2372 if end > start {
2373 line.marks.extend(marks.iter().map(|kind| Mark {
2374 range: start..end,
2375 kind: kind.clone(),
2376 }));
2377 }
2378 }
2379 }
2380
2381 fn walk(&mut self, spans: &[Span], kind: &LineKind, marks: &[MarkKind]) {
2382 let with = |extra: MarkKind| {
2383 let mut marks = marks.to_vec();
2384 marks.push(extra);
2385 marks
2386 };
2387 for (index, span) in spans.iter().enumerate() {
2388 let block_follows = matches!(
2389 spans.get(index + 1),
2390 Some(
2391 Span::List { .. }
2392 | Span::BlockQuote(_)
2393 | Span::CodeBlock { .. }
2394 | Span::Heading { .. }
2395 | Span::Table { .. }
2396 | Span::Rule
2397 | Span::Indent { .. }
2398 )
2399 );
2400 match span {
2401 Span::Text(text) => self.append(text, kind, marks),
2402 Span::Bold(children) => self.walk(children, kind, &with(MarkKind::Bold)),
2403 Span::Italic(children) => self.walk(children, kind, &with(MarkKind::Italic)),
2404 Span::Strike(children) => self.walk(children, kind, &with(MarkKind::Strike)),
2405 Span::Underline(children) => self.walk(children, kind, &with(MarkKind::Underline)),
2406 Span::Superscript(children) => {
2407 self.walk(children, kind, &with(MarkKind::Superscript))
2408 }
2409 Span::Subscript(children) => self.walk(children, kind, &with(MarkKind::Subscript)),
2410 Span::Sized(FontSize::Small, children) => {
2411 self.walk(children, kind, &with(MarkKind::Size(SizeStep::Small)))
2412 }
2413 Span::Sized(FontSize::Large, children) => {
2414 self.walk(children, kind, &with(MarkKind::Size(SizeStep::Large)))
2415 }
2416 Span::Sized(_, children) => self.walk(children, kind, marks),
2417 Span::Colored {
2418 color,
2419 background,
2420 children,
2421 } => {
2422 let mut colored = marks.to_vec();
2423 colored.extend(color.map(MarkKind::Color));
2424 colored.extend(background.map(MarkKind::Highlight));
2425 self.walk(children, kind, &colored)
2426 }
2427 Span::Code(text) => self.append(text, kind, &with(MarkKind::Code)),
2428 Span::Link { url, children } => {
2429 self.walk(children, kind, &with(MarkKind::Link(url.clone())))
2430 }
2431 Span::Mention { name, .. } => {
2432 self.append(&format!("@{}", name.trim_start_matches('@')), kind, marks)
2433 }
2434 Span::Rule if *kind == LineKind::Text => {
2435 self.lines.push(DraftLine {
2436 kind: LineKind::Rule,
2437 number: None,
2438 content: RULE_MARK.to_string(),
2439 marks: Vec::new(),
2440 });
2441 self.open = false;
2442 }
2443 Span::Indent { level, children }
2444 if *kind == LineKind::Text
2445 && !children
2446 .iter()
2447 .any(|child| matches!(child, Span::Heading { .. })) =>
2448 {
2449 let indent = LineKind::Indent((*level).clamp(1, MAX_INDENT));
2450 self.start_line(&indent, None);
2451 self.walk(children, &indent, marks);
2452 self.open = false;
2453 }
2454 Span::Indent { children, .. } => self.walk(children, kind, marks),
2455 Span::LineBreak | Span::Rule if !self.open || block_follows => {}
2456 Span::LineBreak | Span::Rule => {
2457 let continued = match kind {
2458 LineKind::Quote | LineKind::Code(_) | LineKind::Indent(_) => kind.clone(),
2459 _ => LineKind::Text,
2460 };
2461 self.start_line(&continued, None);
2462 }
2463 Span::Heading { level, children } => {
2464 let heading = LineKind::Heading((*level).clamp(1, MAX_HEADING));
2465 self.start_line(&heading, None);
2466 self.walk(children, &heading, marks);
2467 self.open = false;
2468 }
2469 Span::CodeBlock { language, code } => {
2470 let code_kind = LineKind::Code(language.clone());
2471 for line in code.trim_end_matches('\n').split('\n') {
2472 self.start_line(&code_kind, None);
2473 self.append(line, &code_kind, &[]);
2474 }
2475 self.open = false;
2476 }
2477 Span::BlockQuote(children) => {
2478 self.start_line(&LineKind::Quote, None);
2479 self.walk(children, &LineKind::Quote, marks);
2480 self.open = false;
2481 }
2482 Span::List {
2483 ordered,
2484 start,
2485 items,
2486 } => {
2487 let depth = if kind.is_list() {
2488 (kind.depth() + 1).min(MAX_DEPTH)
2489 } else {
2490 0
2491 };
2492 let item_kind = if *ordered {
2493 LineKind::Numbered(depth)
2494 } else {
2495 LineKind::Bullet(depth)
2496 };
2497 for (position, item) in items.iter().enumerate() {
2498 let number = (position == 0).then_some(*start);
2499 self.start_line(&item_kind, number);
2500 self.walk(item, &item_kind, marks);
2501 }
2502 self.open = false;
2503 }
2504 Span::Table { rows, .. } => {
2505 let rows = rows
2506 .iter()
2507 .map(|row| row.iter().map(|cell| cell_text(cell)).collect())
2508 .collect();
2509 self.lines.push(table_line(Table::from_rows(rows)));
2510 self.open = false;
2511 }
2512 Span::Image { .. } | Span::Quote { .. } | Span::CustomEmoji { .. } => {}
2513 }
2514 }
2515 }
2516
2517 fn finish(mut self) -> Vec<DraftLine> {
2518 let blank =
2519 |line: &DraftLine| line.kind == LineKind::Text && line.content.trim().is_empty();
2520 while self.lines.len() > 1 && self.lines.last().is_some_and(blank) {
2521 self.lines.pop();
2522 }
2523 while self.lines.len() > 1 && self.lines.first().is_some_and(blank) {
2524 self.lines.remove(0);
2525 }
2526 if self.lines.is_empty() {
2527 self.lines.push(DraftLine::text(""));
2528 }
2529 self.lines
2530 }
2531}
2532
2533#[cfg(test)]
2534mod tests {
2535 use super::*;
2536 use crate::html_to_spans;
2537
2538 fn typed(draft: &mut Draft, text: &str) {
2539 let mut typing: Option<TypingStyle> = None;
2540 for character in text.chars() {
2541 let cursor = draft.text().len();
2542 let mut next = draft.text().to_owned();
2543 next.push(character);
2544 let cursor = draft.apply_edit(&next, cursor + character.len_utf8(), typing.as_ref());
2545 typing = draft.convert_typed(cursor).map(|(_, style)| style);
2546 draft.take_edits();
2547 }
2548 }
2549
2550 #[test]
2551 fn object_marks_stay_in_the_html_and_leave_the_plain_text() {
2552 let draft = Draft::plain("a \u{FFFC} b");
2553 assert_eq!(draft.plain_text(), "a b");
2554 assert_eq!(draft.to_html(), "a \u{FFFC} b");
2555 assert!(Draft::plain("\u{FFFC}").is_blank());
2556 }
2557
2558 #[test]
2559 fn slices_without_objects_keep_the_formatting_of_the_rest() {
2560 let mut draft = Draft::plain("ab\u{FFFC}cd");
2561 draft.toggle(0..draft.text().len(), MarkKind::Bold);
2562 let lines = draft.slice_without_objects(0..draft.text().len());
2563 assert_eq!(lines.len(), 1);
2564 assert_eq!(lines[0].content, "abcd");
2565 assert_eq!(
2566 lines[0].marks,
2567 [Mark {
2568 range: 0..4,
2569 kind: MarkKind::Bold
2570 }]
2571 );
2572 }
2573
2574 #[test]
2575 fn lines_round_trip_through_json_with_formatting() {
2576 let mut draft = Draft::plain("bold\nitem\nafter");
2577 draft.toggle(0..4, MarkKind::Bold);
2578 draft.set_line_kind(1, LineKind::Bullet(0), None, 0);
2579 let json = serde_json::to_string(&draft.to_lines()).unwrap();
2580 let lines: Vec<DraftLine> = serde_json::from_str(&json).unwrap();
2581 let restored = Draft::from_lines(&lines);
2582 assert_eq!(restored.text(), draft.text());
2583 assert_eq!(restored.to_html(), draft.to_html());
2584 assert_eq!(restored.lines(), draft.lines());
2585 }
2586
2587 fn typed_draft(text: &str) -> Draft {
2588 let mut draft = Draft::default();
2589 typed(&mut draft, text);
2590 draft
2591 }
2592
2593 fn mark(range: Range<usize>, kind: MarkKind) -> Mark {
2594 Mark { range, kind }
2595 }
2596
2597 #[test]
2598 fn typed_markdown_becomes_formatting() {
2599 let draft = typed_draft("a **bold** and *it* or _it_ ~~gone~~ `code`");
2600 assert_eq!(draft.text(), "a bold and it or it gone code");
2601 assert_eq!(
2602 draft.marks(),
2603 [
2604 mark(2..6, MarkKind::Bold),
2605 mark(11..13, MarkKind::Bold),
2606 mark(17..19, MarkKind::Italic),
2607 mark(20..24, MarkKind::Strike),
2608 mark(25..29, MarkKind::Code),
2609 ]
2610 );
2611 }
2612
2613 #[test]
2614 fn typed_link_keeps_the_label_and_carries_the_url() {
2615 let draft = typed_draft("see [docs](https://example.com)");
2616 assert_eq!(draft.text(), "see docs");
2617 assert_eq!(
2618 draft.marks(),
2619 [mark(4..8, MarkKind::Link("https://example.com".into()))]
2620 );
2621 }
2622
2623 fn typed_autolinked(draft: &mut Draft, text: &str) {
2624 for character in text.chars() {
2625 let mut next = draft.text().to_owned();
2626 next.push(character);
2627 let cursor = next.len();
2628 draft.apply_edit(&next, cursor, None);
2629 draft.autolink_typed(cursor);
2630 draft.take_edits();
2631 }
2632 }
2633
2634 fn autolinked(text: &str) -> Draft {
2635 let mut draft = Draft::default();
2636 typed_autolinked(&mut draft, text);
2637 draft
2638 }
2639
2640 fn edited(draft: &mut Draft, range: Range<usize>, replacement: &str) {
2641 let mut next = draft.text().to_owned();
2642 next.replace_range(range.clone(), replacement);
2643 draft.apply_edit(&next, range.start + replacement.len(), None);
2644 }
2645
2646 #[test]
2647 fn typed_url_followed_by_a_space_becomes_a_link() {
2648 let draft = autolinked("https://example.com ");
2649 assert_eq!(
2650 draft.marks(),
2651 [mark(0..19, MarkKind::Link("https://example.com".into()))]
2652 );
2653 }
2654
2655 #[test]
2656 fn typed_url_followed_by_a_newline_becomes_a_link() {
2657 let draft = autolinked("a mailto:x@y.de\n");
2658 assert_eq!(
2659 draft.marks(),
2660 [mark(2..15, MarkKind::Link("mailto:x@y.de".into()))]
2661 );
2662 }
2663
2664 #[test]
2665 fn autolink_leaves_trailing_punctuation_out_and_adds_the_scheme() {
2666 let draft = autolinked("see www.x.de. ");
2667 assert_eq!(
2668 draft.marks(),
2669 [mark(4..12, MarkKind::Link("https://www.x.de".into()))]
2670 );
2671 let wiki = autolinked("https://a.b/x_(y) ");
2672 assert_eq!(
2673 wiki.marks(),
2674 [mark(0..17, MarkKind::Link("https://a.b/x_(y)".into()))]
2675 );
2676 let bracketed = autolinked("https://a.b) ");
2677 assert_eq!(
2678 bracketed.marks(),
2679 [mark(0..11, MarkKind::Link("https://a.b".into()))]
2680 );
2681 }
2682
2683 #[test]
2684 fn autolink_starts_after_any_non_alphanumeric_character() {
2685 let bracketed = autolinked("(https://a.b) ");
2686 assert_eq!(
2687 bracketed.marks(),
2688 [mark(1..12, MarkKind::Link("https://a.b".into()))]
2689 );
2690 let quoted = autolinked("\"www.x.de\" ");
2691 assert_eq!(
2692 quoted.marks(),
2693 [mark(1..9, MarkKind::Link("https://www.x.de".into()))]
2694 );
2695 let colon = autolinked("see:https://a.b ");
2696 assert_eq!(
2697 colon.marks(),
2698 [mark(4..15, MarkKind::Link("https://a.b".into()))]
2699 );
2700 assert!(autolinked("xhttps://a.b ").marks().is_empty());
2701 }
2702
2703 #[test]
2704 fn a_link_labelled_with_a_bare_domain_keeps_its_url_when_relabelled() {
2705 let mut draft = Draft::plain("example.com");
2706 draft.set_link(0..11, "example.com");
2707 edited(&mut draft, 0..11, "our site");
2708 assert_eq!(
2709 draft.marks(),
2710 [mark(0..8, MarkKind::Link("https://example.com".into()))]
2711 );
2712 }
2713
2714 #[test]
2715 fn autolink_skips_plain_words_code_and_existing_links() {
2716 assert!(autolinked("example.com ").marks().is_empty());
2717 assert!(autolinked("http:// ").marks().is_empty());
2718 let mut block = Draft::from_markdown("```\nhttps://a.b");
2719 typed_autolinked(&mut block, " ");
2720 assert!(block.marks().is_empty());
2721 let mut code = Draft::plain("https://a.b");
2722 code.toggle(0..11, MarkKind::Code);
2723 typed_autolinked(&mut code, " ");
2724 assert_eq!(code.marks(), [mark(0..11, MarkKind::Code)]);
2725 let mut linked = Draft::plain("https://a.b");
2726 linked.set_link(0..11, "https://other.de");
2727 typed_autolinked(&mut linked, " ");
2728 assert_eq!(
2729 linked.marks(),
2730 [mark(0..11, MarkKind::Link("https://other.de".into()))]
2731 );
2732 }
2733
2734 #[test]
2735 fn markdown_import_links_bare_urls_outside_code_and_labels() {
2736 let draft = Draft::from_markdown("go to https://a.b now");
2737 assert_eq!(
2738 draft.marks(),
2739 [mark(6..17, MarkKind::Link("https://a.b".into()))]
2740 );
2741 assert_eq!(
2742 Draft::from_markdown("run `https://a.b` now").marks(),
2743 [mark(4..15, MarkKind::Code)]
2744 );
2745 let labelled = Draft::from_markdown("[https://a.b](https://c.d)");
2746 assert_eq!(
2747 labelled.marks(),
2748 [mark(0..11, MarkKind::Link("https://c.d".into()))]
2749 );
2750 assert!(has_markdown("x https://a.b y"));
2751 }
2752
2753 #[test]
2754 fn editing_an_auto_link_moves_its_url() {
2755 let mut draft = autolinked("https://a.bc ");
2756 edited(&mut draft, 11..12, "d");
2757 assert_eq!(
2758 draft.marks(),
2759 [mark(0..12, MarkKind::Link("https://a.bd".into()))]
2760 );
2761 edited(&mut draft, 11..11, "e");
2762 assert_eq!(
2763 draft.marks(),
2764 [mark(0..13, MarkKind::Link("https://a.bed".into()))]
2765 );
2766 }
2767
2768 #[test]
2769 fn editing_a_labelled_link_keeps_its_url() {
2770 let mut draft = typed_draft("[docs](https://example.com)");
2771 edited(&mut draft, 2..2, "x");
2772 assert_eq!(
2773 draft.marks(),
2774 [mark(0..5, MarkKind::Link("https://example.com".into()))]
2775 );
2776 }
2777
2778 #[test]
2779 fn breaking_an_auto_link_into_non_url_text_removes_it() {
2780 let mut draft = autolinked("https://a.bc ");
2781 edited(&mut draft, 9..9, " ");
2782 assert!(draft.marks().is_empty());
2783 }
2784
2785 #[test]
2786 fn an_auto_link_can_be_relabelled_or_unlinked() {
2787 let mut draft = autolinked("https://a.bc ");
2788 assert_eq!(draft.link_in(0..4), Some("https://a.bc".into()));
2789 draft.set_link(0..12, "https://other.de");
2790 assert_eq!(
2791 draft.marks(),
2792 [mark(0..12, MarkKind::Link("https://other.de".into()))]
2793 );
2794 edited(&mut draft, 12..12, "x");
2795 draft.set_link(0..12, "");
2796 assert!(draft.marks().is_empty());
2797 }
2798
2799 #[test]
2800 fn snake_case_and_spaced_stars_stay_text() {
2801 assert_eq!(typed_draft("snake_case_name").text(), "snake_case_name");
2802 assert_eq!(typed_draft("2 * 3 * 4").text(), "2 * 3 * 4");
2803 assert!(typed_draft("a** b**").marks().is_empty());
2804 }
2805
2806 #[test]
2807 fn typing_at_the_end_of_bold_continues_it_but_not_after_a_link() {
2808 let mut draft = Draft::plain("b");
2809 draft.toggle(0..1, MarkKind::Bold);
2810 typed(&mut draft, "x");
2811 assert_eq!(draft.marks(), [mark(0..2, MarkKind::Bold)]);
2812 let converted = typed_draft("**b**x");
2813 assert_eq!(converted.marks(), [mark(0..1, MarkKind::Bold)]);
2814 let mut linked = typed_draft("[a](u)");
2815 typed(&mut linked, "b");
2816 assert_eq!(
2817 linked.marks(),
2818 [mark(0..1, MarkKind::Link("https://u".into()))]
2819 );
2820 }
2821
2822 #[test]
2823 fn typing_style_switches_bold_on_and_off_for_the_next_text() {
2824 let mut draft = Draft::plain("ab");
2825 let typing = TypingStyle {
2826 at: 2,
2827 add: vec![MarkKind::Bold],
2828 remove: Vec::new(),
2829 };
2830 draft.apply_edit("abc", 3, Some(&typing));
2831 assert_eq!(draft.marks(), [mark(2..3, MarkKind::Bold)]);
2832 let off = TypingStyle {
2833 at: 3,
2834 add: Vec::new(),
2835 remove: vec![MarkKind::Bold],
2836 };
2837 draft.apply_edit("abcd", 4, Some(&off));
2838 assert_eq!(draft.marks(), [mark(2..3, MarkKind::Bold)]);
2839 }
2840
2841 #[test]
2842 fn toggle_on_a_mixed_selection_formats_all_then_clears() {
2843 let mut draft = Draft::plain("hello world");
2844 draft.toggle(0..5, MarkKind::Bold);
2845 assert_eq!(draft.state(0..11, &MarkKind::Bold), FormatState::Mixed);
2846 draft.toggle(0..11, MarkKind::Bold);
2847 assert_eq!(draft.state(0..11, &MarkKind::Bold), FormatState::On);
2848 draft.toggle(0..11, MarkKind::Bold);
2849 assert_eq!(draft.state(0..11, &MarkKind::Bold), FormatState::Off);
2850 assert!(draft.marks().is_empty());
2851 }
2852
2853 #[test]
2854 fn deleting_inside_and_across_marks_shifts_and_clips() {
2855 let mut draft = Draft::plain("aa bold cc");
2856 draft.toggle(3..7, MarkKind::Bold);
2857 draft.apply_edit("aa bld cc", 4, None);
2858 assert_eq!(draft.marks(), [mark(3..6, MarkKind::Bold)]);
2859 draft.apply_edit("ald cc", 1, None);
2860 assert_eq!(draft.marks(), [mark(1..3, MarkKind::Bold)]);
2861 draft.apply_edit("XXald cc", 2, None);
2862 assert_eq!(draft.marks(), [mark(3..5, MarkKind::Bold)]);
2863 }
2864
2865 #[test]
2866 fn repeated_characters_are_attributed_to_the_cursor() {
2867 let mut draft = Draft::plain("aa");
2868 draft.toggle(0..1, MarkKind::Bold);
2869 draft.apply_edit("aaa", 2, None);
2870 assert_eq!(draft.marks(), [mark(0..2, MarkKind::Bold)]);
2871 }
2872
2873 #[test]
2874 fn list_shortcuts_turn_lines_into_items() {
2875 let draft = typed_draft("- one");
2876 assert_eq!(draft.text(), "• one");
2877 assert_eq!(draft.lines(), [LineKind::Bullet(0)]);
2878 let numbered = typed_draft("1. one");
2879 assert_eq!(numbered.text(), "1. one");
2880 assert_eq!(numbered.lines(), [LineKind::Numbered(0)]);
2881 let quote = typed_draft(">said");
2882 assert_eq!(quote.text(), "said");
2883 assert_eq!(quote.lines(), [LineKind::Quote]);
2884 let spaced = typed_draft("> said");
2885 assert_eq!(spaced.text(), " said");
2886 assert_eq!(spaced.lines(), [LineKind::Quote]);
2887 }
2888
2889 #[test]
2890 fn enter_continues_a_list_and_ends_it_on_an_empty_item() {
2891 let mut draft = typed_draft("1. one");
2892 let cursor = draft.break_line(draft.text().len(), false).unwrap();
2893 assert_eq!(draft.text(), "1. one\n2. ");
2894 assert_eq!(cursor, draft.text().len());
2895 typed(&mut draft, "two");
2896 let cursor = draft.break_line(draft.text().len(), false).unwrap();
2897 let cursor = draft.break_line(cursor, false).unwrap();
2898 assert_eq!(draft.text(), "1. one\n2. two\n");
2899 assert_eq!(cursor, draft.text().len());
2900 assert_eq!(draft.lines()[2], LineKind::Text);
2901 assert_eq!(Draft::plain("x").break_line(1, false), None);
2902 }
2903
2904 #[test]
2905 fn enter_in_the_middle_of_an_item_splits_it_and_renumbers() {
2906 let mut draft = Draft::from_markdown("1. ab\n2. c");
2907 draft.break_line(4, false).unwrap();
2908 assert_eq!(draft.text(), "1. a\n2. b\n3. c");
2909 let edits = draft.take_edits();
2910 assert_eq!(map_offset(&edits, 4), 8);
2911 }
2912
2913 #[test]
2914 fn tab_nests_and_shift_tab_lifts_list_items() {
2915 let mut draft = Draft::from_markdown("- a\n- b");
2916 assert!(draft.indent(6..6, false));
2917 assert_eq!(draft.lines(), [LineKind::Bullet(0), LineKind::Bullet(1)]);
2918 assert_eq!(draft.text(), "• a\n◦ b");
2919 assert!(draft.indent(draft.text().len()..draft.text().len(), true));
2920 assert!(draft.indent(draft.text().len()..draft.text().len(), true));
2921 assert_eq!(draft.text(), "• a\nb");
2922 assert!(!Draft::plain("x").indent(0..0, false));
2923 }
2924
2925 #[test]
2926 fn nested_numbering_counts_per_level() {
2927 let draft = Draft::from_markdown("1. a\n 1. x\n 2. y\n2. b");
2928 assert_eq!(draft.text(), "1. a\n1. x\n2. y\n2. b");
2929 }
2930
2931 #[test]
2932 fn backspace_at_an_item_start_drops_the_bullet() {
2933 let mut draft = Draft::from_markdown("- a");
2934 let cursor = draft.backspace_at_start(bullet_marker(0).len()).unwrap();
2935 assert_eq!((draft.text(), cursor), ("a", 0));
2936 assert_eq!(draft.lines(), [LineKind::Text]);
2937 }
2938
2939 #[test]
2940 fn typing_before_a_bullet_lands_after_it() {
2941 let mut draft = Draft::from_markdown("- a");
2942 let marker = bullet_marker(0);
2943 let cursor = draft.apply_edit(&format!("x{marker}a"), 1, None);
2944 assert_eq!(draft.text(), format!("{marker}xa"));
2945 assert_eq!(cursor, marker.len() + 1);
2946 assert_eq!(
2947 draft.take_edits(),
2948 [
2949 (0..1, String::new()),
2950 (marker.len() + 1..marker.len() + 1, "x".to_owned())
2951 ]
2952 );
2953 }
2954
2955 #[test]
2956 fn a_damaged_marker_turns_the_line_into_text() {
2957 let mut draft = Draft::from_markdown("- a");
2958 draft.apply_edit("•a", 1, None);
2959 assert_eq!(draft.lines(), [LineKind::Text]);
2960 }
2961
2962 #[test]
2963 fn fence_and_enter_open_a_code_block_that_enter_continues() {
2964 let mut draft = typed_draft("```rust");
2965 let cursor = draft.break_line(draft.text().len(), false).unwrap();
2966 assert_eq!((draft.text(), cursor), ("", 0));
2967 assert_eq!(draft.lines(), [LineKind::Code(Some("rust".into()))]);
2968 typed(&mut draft, "fn x() {}");
2969 let cursor = draft.break_line(draft.text().len(), false).unwrap();
2970 assert_eq!(draft.lines().len(), 2);
2971 assert_eq!(draft.break_line(cursor, false), Some(cursor));
2972 assert_eq!(draft.lines()[1], LineKind::Text);
2973 assert_eq!(
2974 draft.to_html(),
2975 "<pre class=\"language-rust skipProofing\" spellcheck=\"false\"><code>fn x() {}</code></pre>"
2976 );
2977 }
2978
2979 #[test]
2980 fn markdown_inside_code_stays_literal() {
2981 let mut draft = typed_draft("```");
2982 let cursor = draft.break_line(3, false).unwrap();
2983 assert_eq!(cursor, 0);
2984 typed(&mut draft, "a **b**");
2985 assert_eq!(draft.text(), "a **b**");
2986 assert!(draft.marks().is_empty());
2987 }
2988
2989 #[test]
2990 fn html_nests_overlapping_marks_and_escapes() {
2991 let mut draft = Draft::plain("a<b & c");
2992 draft.toggle(0..4, MarkKind::Bold);
2993 draft.toggle(2..7, MarkKind::Italic);
2994 assert_eq!(draft.to_html(), "<b>a&lt;<i>b </i></b><i>&amp; c</i>");
2995 }
2996
2997 #[test]
2998 fn html_covers_every_format() {
2999 let draft = Draft::from_markdown(
3000 "**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```",
3001 );
3002 let mut underlined = draft.clone();
3003 underlined.toggle(0..1, MarkKind::Underline);
3004 assert_eq!(
3005 underlined.to_html(),
3006 "<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>\
3007 <blockquote>q1<br>q2</blockquote>\
3008 <ul><li>a<ul><li>b</li></ul></li></ul>\
3009 <ol><li>x</li><li>y</li></ol>\
3010 <pre class=\"language-py skipProofing\" spellcheck=\"false\"><code>print(1)</code></pre>"
3011 );
3012 }
3013
3014 #[test]
3015 fn script_and_size_marks_export_teams_html() {
3016 let mut draft = Draft::plain("x2 H2O big tiny");
3017 draft.toggle(1..2, MarkKind::Superscript);
3018 draft.toggle(4..5, MarkKind::Subscript);
3019 draft.set_size(7..10, Some(SizeStep::Large));
3020 draft.set_size(11..15, Some(SizeStep::Small));
3021 assert_eq!(
3022 draft.to_html(),
3023 "x<sup>2</sup> H<sub>2</sub>O <span style=\"font-size:x-large;\">big</span> \
3024 <span style=\"font-size:xx-small;\">tiny</span>"
3025 );
3026 }
3027
3028 #[test]
3029 fn script_and_size_marks_round_trip_through_html() {
3030 let mut source = Draft::plain("x2 H2O big tiny");
3031 source.toggle(1..2, MarkKind::Superscript);
3032 source.toggle(4..5, MarkKind::Subscript);
3033 source.toggle(7..10, MarkKind::Bold);
3034 source.set_size(7..10, Some(SizeStep::Large));
3035 source.set_size(11..15, Some(SizeStep::Small));
3036 let back = Draft::from_spans(&html_to_spans(&source.to_html()));
3037 assert_eq!(back.text(), source.text());
3038 assert_eq!(back.marks(), source.marks());
3039 }
3040
3041 #[test]
3042 fn inherit_and_pixel_sizes_import_without_a_size_mark() {
3043 let spans = html_to_spans(
3044 "<span style=\"font-size:inherit;\">a</span><span style=\"font-size:14px\">b</span>",
3045 );
3046 assert!(Draft::from_spans(&spans).marks().is_empty());
3047 }
3048
3049 #[test]
3050 fn superscript_and_subscript_exclude_each_other() {
3051 let mut draft = Draft::plain("abcdef");
3052 draft.toggle(0..4, MarkKind::Superscript);
3053 draft.toggle(2..6, MarkKind::Subscript);
3054 assert_eq!(
3055 draft.marks(),
3056 [
3057 mark(0..2, MarkKind::Superscript),
3058 mark(2..6, MarkKind::Subscript)
3059 ]
3060 );
3061 }
3062
3063 #[test]
3064 fn typing_style_switches_between_script_marks() {
3065 let mut style = TypingStyle::default();
3066 style.toggle(MarkKind::Subscript, &[MarkKind::Superscript]);
3067 assert_eq!(
3068 style.apply(vec![MarkKind::Superscript]),
3069 vec![MarkKind::Subscript]
3070 );
3071 }
3072
3073 #[test]
3074 fn size_changes_on_a_partial_range_split_the_mark() {
3075 let mut draft = Draft::plain("abcdef");
3076 draft.set_size(0..6, Some(SizeStep::Large));
3077 draft.set_size(2..4, Some(SizeStep::Small));
3078 assert_eq!(
3079 draft.marks(),
3080 [
3081 mark(2..4, MarkKind::Size(SizeStep::Small)),
3082 mark(0..2, MarkKind::Size(SizeStep::Large)),
3083 mark(4..6, MarkKind::Size(SizeStep::Large)),
3084 ]
3085 );
3086 assert_eq!(draft.size_in(2..4), Some(SizeStep::Small));
3087 assert_eq!(draft.size_in(0..6), None);
3088 draft.set_size(0..6, None);
3089 assert!(draft.marks().is_empty());
3090 }
3091
3092 #[test]
3093 fn ordered_lists_keep_their_start() {
3094 let draft = Draft::from_markdown("3. c\n4. d");
3095 assert_eq!(draft.to_html(), "<ol start=\"3\"><li>c</li><li>d</li></ol>");
3096 }
3097
3098 #[test]
3099 fn spans_round_trip_through_html() {
3100 let source = Draft::from_markdown(
3101 "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",
3102 );
3103 let back = Draft::from_spans(&html_to_spans(&source.to_html()));
3104 assert_eq!(back.text(), source.text());
3105 assert_eq!(back.lines(), source.lines());
3106 assert_eq!(back.marks(), source.marks());
3107 }
3108
3109 #[test]
3110 fn mentions_from_html_come_back_as_at_text() {
3111 let draft = Draft::from_spans(&html_to_spans("hi <at id=\"0\">Ada</at> <b>now</b>"));
3112 assert_eq!(draft.text(), "hi @Ada now");
3113 assert_eq!(draft.marks(), [mark(8..11, MarkKind::Bold)]);
3114 }
3115
3116 #[test]
3117 fn pasted_markdown_is_detected() {
3118 assert!(has_markdown("see **this**"));
3119 assert!(has_markdown("- a\n- b"));
3120 assert!(has_markdown("```\nx\n```"));
3121 assert!(!has_markdown("plain text, 2*3=6 and snake_case"));
3122 }
3123
3124 #[test]
3125 fn slices_carry_formatting_into_another_draft() {
3126 let source = Draft::from_markdown("intro **bold**\n- one\n- two");
3127 let end = source.text().len();
3128 let fragment = source.slice(6..end);
3129 assert_eq!(fragment[0].kind, LineKind::Text);
3130 assert_eq!(fragment[1].kind, LineKind::Bullet(0));
3131 let mut target = Draft::plain("x ");
3132 let cursor = target.insert_lines(2..2, &fragment);
3133 assert_eq!(target.text(), "x bold\n• one\n• two");
3134 assert_eq!(cursor, target.text().len());
3135 assert_eq!(target.marks(), [mark(2..6, MarkKind::Bold)]);
3136 assert_eq!(
3137 target.lines()[1..],
3138 [LineKind::Bullet(0), LineKind::Bullet(0)]
3139 );
3140 }
3141
3142 #[test]
3143 fn markdown_pasted_on_its_own_line_converts_from_the_first_line() {
3144 let raw = "- a\n- b";
3145 let mut draft = Draft::plain("");
3146 draft.apply_edit(raw, raw.len(), None);
3147 let lines = Draft::from_markdown(raw).slice(0..usize::MAX);
3148 let cursor = draft.insert_lines(0..raw.len(), &lines);
3149 assert_eq!(draft.text(), "• a\n• b");
3150 assert_eq!(cursor, draft.text().len());
3151 let mut inline = Draft::plain("x ");
3152 inline.apply_edit("x **b**", 7, None);
3153 let lines = Draft::from_markdown("**b**").slice(0..usize::MAX);
3154 inline.insert_lines(2..7, &lines);
3155 assert_eq!(inline.text(), "x b");
3156 assert_eq!(inline.marks(), [mark(2..3, MarkKind::Bold)]);
3157 }
3158
3159 #[test]
3160 fn a_paste_inside_a_line_puts_the_cursor_after_the_pasted_text() {
3161 let lines = Draft::from_markdown("**big**").slice(0..usize::MAX);
3162 let mut plain = Draft::plain("hello world");
3163 assert_eq!(plain.insert_lines(6..6, &lines), 9);
3164 assert_eq!(plain.text(), "hello bigworld");
3165 let mut item = Draft::from_markdown("- item one");
3166 let before_one = bullet_marker(0).len() + "item ".len();
3167 assert_eq!(
3168 item.insert_lines(before_one..before_one, &lines),
3169 before_one + 3
3170 );
3171 }
3172
3173 #[test]
3174 fn a_selection_ending_at_the_next_line_start_leaves_that_line_alone() {
3175 let mut draft = Draft::plain("first\nsecond");
3176 assert_eq!(
3177 draft.line_state(0..6, &LineKind::Bullet(0)),
3178 FormatState::Off
3179 );
3180 draft.toggle_lines(0..6, LineKind::Bullet(0));
3181 assert_eq!(draft.lines(), [LineKind::Bullet(0), LineKind::Text]);
3182 let end_of_first = draft.line_ranges()[1].start;
3183 assert_eq!(
3184 draft.line_state(0..end_of_first, &LineKind::Bullet(0)),
3185 FormatState::On
3186 );
3187 assert!(draft.indent(0..end_of_first, false));
3188 assert_eq!(draft.lines()[1], LineKind::Text);
3189 }
3190
3191 #[test]
3192 fn links_only_take_http_https_and_mailto() {
3193 assert_eq!(link_url("example.com"), Some("https://example.com".into()));
3194 assert_eq!(link_url("mailto:a@b.test"), Some("mailto:a@b.test".into()));
3195 assert_eq!(link_url("javascript:alert(1)"), None);
3196 assert_eq!(link_url("data:text/html,x"), None);
3197 let typed = typed_draft("[x](javascript:alert)");
3198 assert!(typed.marks().is_empty());
3199 let pasted = Draft::from_markdown("[x](javascript:alert) [y](example.com)");
3200 assert_eq!(
3201 pasted.marks(),
3202 [mark(22..23, MarkKind::Link("https://example.com".into()))]
3203 );
3204 let mut set = Draft::plain("go");
3205 set.set_link(0..2, "javascript:alert(1)");
3206 assert!(set.marks().is_empty());
3207 let spans = Draft::from_spans(&html_to_spans("<a href=\"javascript:x\">bad</a>"));
3208 assert!(spans.marks().is_empty());
3209 }
3210
3211 #[test]
3212 fn code_lines_hold_only_their_content() {
3213 let mut draft = Draft::from_markdown("```\nlet a = 1;\n\u{2003}b\n```");
3214 assert_eq!(draft.text(), "let a = 1;\n\u{2003}b");
3215 assert_eq!(
3216 draft.to_html(),
3217 "<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>let a = 1;<br>\u{2003}b</code></pre>"
3218 );
3219 assert_eq!(draft.backspace_at_start(draft.line_ranges()[1].start), None);
3220 assert_eq!(draft.backspace_at_start(0), Some(0));
3221 assert_eq!(draft.lines()[0], LineKind::Text);
3222 }
3223
3224 #[test]
3225 fn in_code_covers_code_lines_and_the_inside_of_inline_code() {
3226 let draft = Draft::from_markdown("a `cd` e\n```\nx\n```");
3227 assert!(!draft.in_code(2));
3228 assert!(draft.in_code(3));
3229 assert!(!draft.in_code(4));
3230 assert!(draft.in_code(draft.text().len()));
3231 }
3232
3233 #[test]
3234 fn code_indentation_is_kept_on_paste_split_and_send() {
3235 let mut draft = typed_draft("```py");
3236 let cursor = draft.break_line(draft.text().len(), false).unwrap();
3237 let pasted = "def f():\n return 1";
3238 let mut next = draft.text().to_owned();
3239 next.insert_str(cursor, pasted);
3240 draft.apply_edit(&next, cursor + pasted.len(), None);
3241 assert_eq!(
3242 draft.to_html(),
3243 "<pre class=\"language-py skipProofing\" spellcheck=\"false\"><code>def f():<br> return 1</code></pre>"
3244 );
3245 let mut split = Draft::from_markdown("```\n a b\n```");
3246 let after_a = " a".len();
3247 split.break_line(after_a, false).unwrap();
3248 assert_eq!(
3249 split.to_html(),
3250 "<pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code> a<br> b</code></pre>"
3251 );
3252 }
3253
3254 #[test]
3255 fn delete_at_a_line_end_joins_the_next_item_without_its_bullet() {
3256 let mut draft = Draft::from_markdown("- a\n- b");
3257 let end_of_first = draft.line_ranges()[0].end;
3258 assert_eq!(draft.delete_forward(end_of_first), Some(end_of_first));
3259 assert_eq!(draft.text(), "• ab");
3260 assert_eq!(draft.delete_forward(0), Some(bullet_marker(0).len()));
3261 assert_eq!(draft.text(), "• b");
3262 assert_eq!(Draft::plain("a\nb").delete_forward(1), None);
3263 }
3264
3265 #[test]
3266 fn host_and_port_links_are_schemeless() {
3267 assert_eq!(
3268 link_url("localhost:3000"),
3269 Some("https://localhost:3000".into())
3270 );
3271 assert_eq!(
3272 link_url("example.com:8080/x"),
3273 Some("https://example.com:8080/x".into())
3274 );
3275 assert_eq!(link_url("javascript:alert(1)"), None);
3276 assert_eq!(link_url("tel:0123456"), None);
3277 }
3278
3279 #[test]
3280 fn a_quote_stays_a_quote_when_split_or_joined() {
3281 let mut draft = Draft::from_markdown("> a\n> b");
3282 let second = draft.line_ranges()[1].start;
3283 assert_eq!(draft.break_line(second, true), Some(second + 1));
3284 assert_eq!(
3285 draft.lines(),
3286 [LineKind::Quote, LineKind::Quote, LineKind::Quote]
3287 );
3288 let mut joined = Draft::from_markdown("> a\n> b");
3289 let second = joined.line_ranges()[1].start;
3290 assert_eq!(joined.backspace_at_start(second), Some(second - 1));
3291 assert_eq!(
3292 (joined.text(), joined.lines()),
3293 ("ab", &[LineKind::Quote][..])
3294 );
3295 assert_eq!(joined.backspace_at_start(0), Some(0));
3296 assert_eq!(joined.lines(), [LineKind::Text]);
3297 }
3298
3299 #[test]
3300 fn journal_merges_edits_into_ranges_of_the_old_text() {
3301 let mut draft = Draft::plain("a **b** c");
3302 draft.splice(5..7, "", &[]);
3303 draft.splice(2..4, "", &[]);
3304 draft.splice(0..0, "X", &[]);
3305 let edits = draft.take_edits();
3306 assert_eq!(
3307 edits,
3308 [
3309 (0..0, "X".to_owned()),
3310 (2..4, String::new()),
3311 (5..7, String::new())
3312 ]
3313 );
3314 assert_eq!(
3315 reverse_edits(&edits, "a **b** c")[1],
3316 (3..3, "**".to_owned())
3317 );
3318 let mut touching = Draft::plain("abc");
3319 touching.splice(1..2, "XY", &[]);
3320 touching.splice(3..3, "Z", &[]);
3321 assert_eq!(touching.take_edits(), [(1..2, "XYZ".to_owned())]);
3322 }
3323
3324 #[test]
3325 fn trimming_drops_blank_lines_and_outer_spaces() {
3326 let mut draft = Draft::plain("\n hi **x** \n\n");
3327 draft.toggle(6..11, MarkKind::Bold);
3328 let trimmed = draft.trimmed();
3329 assert_eq!(trimmed.text(), "hi **x**");
3330 assert_eq!(trimmed.marks(), [mark(3..8, MarkKind::Bold)]);
3331 }
3332
3333 #[test]
3334 fn toolbar_line_toggles_apply_to_every_selected_line() {
3335 let mut draft = Draft::plain("a\nb");
3336 draft.toggle_lines(0..3, LineKind::Numbered(0));
3337 assert_eq!(draft.text(), "1. a\n2. b");
3338 assert_eq!(
3339 draft.line_state(0..4, &LineKind::Numbered(0)),
3340 FormatState::On
3341 );
3342 draft.toggle_lines(0..9, LineKind::Bullet(0));
3343 assert_eq!(draft.text(), "• a\n• b");
3344 let end = draft.text().len();
3345 draft.toggle_lines(0..end, LineKind::Bullet(0));
3346 assert_eq!(draft.text(), "a\nb");
3347 }
3348
3349 #[test]
3350 fn links_are_set_replaced_and_removed() {
3351 let mut draft = Draft::plain("go here");
3352 draft.set_link(3..7, "https://a.test");
3353 assert_eq!(draft.link_in(4..4), Some("https://a.test".into()));
3354 draft.set_link(3..7, "");
3355 assert!(draft.marks().is_empty());
3356 let end = draft.insert_link(7, " https://b.test", "https://b.test");
3357 assert_eq!(end, draft.text().len());
3358 }
3359}