BlueGit

ict rusty-teams

Files

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

draft.rs

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