1use std::fmt;
8use std::sync::Arc;
9
10use unicode_segmentation::UnicodeSegmentation;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PartialOrd, Ord)]
14pub enum Size {
15 Small,
16 #[default]
17 Normal,
18 Large,
19 Huge,
20}
21
22impl Size {
23 pub const ALL: [Size; 4] = [Size::Small, Size::Normal, Size::Large, Size::Huge];
24
25 pub const fn label(self) -> &'static str {
26 match self {
27 Size::Small => "Small",
28 Size::Normal => "Normal",
29 Size::Large => "Large",
30 Size::Huge => "Huge",
31 }
32 }
33
34 pub const fn scale(self) -> f32 {
36 match self {
37 Size::Small => 0.85,
38 Size::Normal => 1.0,
39 Size::Large => 1.3,
40 Size::Huge => 1.7,
41 }
42 }
43
44 pub(crate) const fn code(self) -> u32 {
45 match self {
46 Size::Small => 0,
47 Size::Normal => 1,
48 Size::Large => 2,
49 Size::Huge => 3,
50 }
51 }
52
53 pub(crate) const fn from_code(code: u32) -> Self {
54 match code {
55 0 => Size::Small,
56 2 => Size::Large,
57 3 => Size::Huge,
58 _ => Size::Normal,
59 }
60 }
61}
62
63impl fmt::Display for Size {
64 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65 f.write_str(self.label())
66 }
67}
68
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
71pub enum Mark {
72 Bold,
73 Italic,
74 Underline,
75 Strikethrough,
76}
77
78impl Mark {
79 pub const ALL: [Mark; 4] = [
80 Mark::Bold,
81 Mark::Italic,
82 Mark::Underline,
83 Mark::Strikethrough,
84 ];
85
86 pub const fn label(self) -> &'static str {
87 match self {
88 Mark::Bold => "Bold",
89 Mark::Italic => "Italic",
90 Mark::Underline => "Underline",
91 Mark::Strikethrough => "Strikethrough",
92 }
93 }
94}
95
96#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
98pub struct Style {
99 pub bold: bool,
100 pub italic: bool,
101 pub underline: bool,
102 pub strikethrough: bool,
103 pub size: Size,
104 pub link: Option<Arc<str>>,
106}
107
108impl Style {
109 pub fn has(&self, mark: Mark) -> bool {
110 match mark {
111 Mark::Bold => self.bold,
112 Mark::Italic => self.italic,
113 Mark::Underline => self.underline,
114 Mark::Strikethrough => self.strikethrough,
115 }
116 }
117
118 pub fn set(&mut self, mark: Mark, on: bool) {
119 match mark {
120 Mark::Bold => self.bold = on,
121 Mark::Italic => self.italic = on,
122 Mark::Underline => self.underline = on,
123 Mark::Strikethrough => self.strikethrough = on,
124 }
125 }
126
127 pub fn with(mut self, mark: Mark) -> Self {
128 self.set(mark, true);
129 self
130 }
131
132 pub fn sized(mut self, size: Size) -> Self {
133 self.size = size;
134 self
135 }
136
137 pub fn linked(mut self, url: impl Into<Arc<str>>) -> Self {
138 self.link = Some(url.into());
139 self
140 }
141
142 pub fn is_plain(&self) -> bool {
144 *self == Style::default()
145 }
146
147 pub(crate) fn same_face(&self, other: &Style) -> bool {
150 self.bold == other.bold && self.italic == other.italic
151 }
152}
153
154#[derive(Debug, Clone, PartialEq, Eq)]
156pub struct Run {
157 pub text: String,
158 pub style: Style,
159}
160
161impl Run {
162 pub fn new(text: impl Into<String>, style: Style) -> Self {
163 Self {
164 text: text.into(),
165 style,
166 }
167 }
168
169 pub fn plain(text: impl Into<String>) -> Self {
170 Self::new(text, Style::default())
171 }
172}
173
174#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
176pub enum BlockKind {
177 #[default]
178 Paragraph,
179 Bullet,
181 Numbered,
183 Quote,
185}
186
187impl BlockKind {
188 pub(crate) const fn code(self) -> u32 {
189 match self {
190 BlockKind::Paragraph => 0,
191 BlockKind::Bullet => 1,
192 BlockKind::Numbered => 2,
193 BlockKind::Quote => 3,
194 }
195 }
196
197 pub(crate) const fn from_code(code: u32) -> Self {
198 match code {
199 1 => BlockKind::Bullet,
200 2 => BlockKind::Numbered,
201 3 => BlockKind::Quote,
202 _ => BlockKind::Paragraph,
203 }
204 }
205
206 pub fn is_list(self) -> bool {
207 matches!(self, BlockKind::Bullet | BlockKind::Numbered)
208 }
209}
210
211#[derive(Debug, Clone, PartialEq, Eq)]
216pub struct Block {
217 kind: BlockKind,
218 runs: Vec<Run>,
219}
220
221impl Default for Block {
222 fn default() -> Self {
223 Self::new(BlockKind::Paragraph)
224 }
225}
226
227impl Block {
228 pub fn new(kind: BlockKind) -> Self {
230 Self {
231 kind,
232 runs: vec![Run::plain("")],
233 }
234 }
235
236 pub fn with_runs(kind: BlockKind, runs: impl IntoIterator<Item = Run>) -> Self {
238 let mut block = Self {
239 kind,
240 runs: runs.into_iter().collect(),
241 };
242 block.normalise();
243 block
244 }
245
246 pub fn paragraph(text: impl Into<String>) -> Self {
247 Self::with_runs(BlockKind::Paragraph, [Run::plain(text)])
248 }
249
250 pub fn kind(&self) -> BlockKind {
251 self.kind
252 }
253
254 pub fn set_kind(&mut self, kind: BlockKind) {
255 self.kind = kind;
256 }
257
258 pub fn runs(&self) -> &[Run] {
259 &self.runs
260 }
261
262 pub fn text(&self) -> String {
263 self.runs.iter().map(|run| run.text.as_str()).collect()
264 }
265
266 pub fn len(&self) -> usize {
268 self.runs.iter().map(|run| run.text.len()).sum()
269 }
270
271 pub fn is_empty(&self) -> bool {
272 self.len() == 0
273 }
274
275 pub fn style_before(&self, offset: usize) -> &Style {
278 let mut start = 0;
279 for run in &self.runs {
280 let end = start + run.text.len();
281 if offset <= end && (offset > start || start == 0) && !run.text.is_empty() {
282 return &run.style;
283 }
284 start = end;
285 }
286 self.runs
287 .first()
288 .map_or_else(|| empty_style(), |run| &run.style)
289 }
290
291 pub fn style_after(&self, offset: usize) -> Option<&Style> {
293 let mut start = 0;
294 for run in &self.runs {
295 let end = start + run.text.len();
296 if offset >= start && offset < end {
297 return Some(&run.style);
298 }
299 start = end;
300 }
301 None
302 }
303
304 pub fn slice(&self, start: usize, end: usize) -> Vec<Run> {
306 let mut out = Vec::new();
307 let mut at = 0;
308 for run in &self.runs {
309 let run_end = at + run.text.len();
310 let from = start.max(at);
311 let to = end.min(run_end);
312 if from < to {
313 out.push(Run::new(&run.text[from - at..to - at], run.style.clone()));
314 }
315 at = run_end;
316 }
317 if out.is_empty() {
318 out.push(Run::new("", self.style_before(start).clone()));
319 }
320 out
321 }
322
323 fn normalise(&mut self) {
324 let fallback = self.runs.first().map(|run| run.style.clone());
325 let mut runs: Vec<Run> = Vec::with_capacity(self.runs.len());
326 for run in self.runs.drain(..) {
327 if run.text.is_empty() {
328 continue;
329 }
330 match runs.last_mut() {
331 Some(last) if last.style == run.style => last.text.push_str(&run.text),
332 _ => runs.push(run),
333 }
334 }
335 if runs.is_empty() {
336 runs.push(Run::new("", fallback.unwrap_or_default()));
337 }
338 self.runs = runs;
339 }
340
341 fn cut(&mut self, offset: usize) -> usize {
344 let mut at = 0;
345 for index in 0..self.runs.len() {
346 let len = self.runs[index].text.len();
347 if offset == at {
348 return index;
349 }
350 if offset < at + len {
351 let tail = self.runs[index].text.split_off(offset - at);
352 let style = self.runs[index].style.clone();
353 self.runs.insert(index + 1, Run::new(tail, style));
354 return index + 1;
355 }
356 at += len;
357 }
358 self.runs.len()
359 }
360
361 fn split_off(&mut self, offset: usize) -> Vec<Run> {
363 let style = self.style_before(offset).clone();
364 let index = self.cut(offset);
365 let mut tail = self.runs.split_off(index);
366 if tail.is_empty() {
367 tail.push(Run::new("", style.clone()));
368 }
369 if self.runs.is_empty() {
370 self.runs.push(Run::new("", style));
371 }
372 self.normalise();
373 tail
374 }
375
376 fn insert_runs(&mut self, offset: usize, runs: Vec<Run>) {
377 let tail = self.split_off(offset);
378 if self.is_empty() {
379 self.runs.clear();
380 }
381 self.runs.extend(runs);
382 self.runs
383 .extend(tail.into_iter().filter(|run| !run.text.is_empty()));
384 self.normalise();
385 }
386
387 fn remove(&mut self, start: usize, end: usize) {
388 if start >= end {
389 return;
390 }
391 let keep = self
392 .style_after(start)
393 .unwrap_or_else(|| self.style_before(start))
394 .clone();
395 let mut tail = self.split_off(end);
396 self.split_off(start);
397 if self.is_empty() {
398 self.runs = vec![Run::new("", keep)];
399 }
400 self.runs.append(&mut tail);
401 self.normalise();
402 }
403
404 fn restyle(&mut self, start: usize, end: usize, change: &impl Fn(&mut Style)) {
405 if self.is_empty() {
406 if let Some(run) = self.runs.first_mut() {
407 change(&mut run.style);
408 }
409 return;
410 }
411 if start >= end {
412 return;
413 }
414 let first = self.cut(start);
415 let last = self.cut(end);
416 for run in &mut self.runs[first..last] {
417 change(&mut run.style);
418 }
419 self.normalise();
420 }
421
422 fn next_boundary(&self, text: &str, offset: usize) -> Option<usize> {
424 let rest = text.get(offset..)?;
425 let grapheme = rest.graphemes(true).next()?;
426 Some(offset + grapheme.len())
427 }
428
429 fn previous_boundary(&self, text: &str, offset: usize) -> Option<usize> {
430 let head = text.get(..offset)?;
431 head.grapheme_indices(true).next_back().map(|(at, _)| at)
432 }
433
434 fn link_range(&self, offset: usize) -> Option<(usize, usize, Arc<str>)> {
437 let link = self
438 .style_after(offset)
439 .and_then(|style| style.link.clone())
440 .or_else(|| {
441 (offset > 0)
442 .then(|| self.style_before(offset).link.clone())
443 .flatten()
444 })?;
445 let mut ranges = Vec::new();
446 let mut at = 0;
447 for run in &self.runs {
448 let end = at + run.text.len();
449 ranges.push((at, end, run.style.link.as_ref() == Some(&link)));
450 at = end;
451 }
452 let index = ranges
453 .iter()
454 .position(|(start, end, linked)| *linked && *start <= offset && offset <= *end)?;
455 let mut first = index;
456 while first > 0 && ranges[first - 1].2 {
457 first -= 1;
458 }
459 let mut last = index;
460 while last + 1 < ranges.len() && ranges[last + 1].2 {
461 last += 1;
462 }
463 Some((ranges[first].0, ranges[last].1, link))
464 }
465}
466
467fn empty_style() -> &'static Style {
468 static PLAIN: std::sync::OnceLock<Style> = std::sync::OnceLock::new();
469 PLAIN.get_or_init(Style::default)
470}
471
472#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PartialOrd, Ord)]
474pub struct Position {
475 pub block: usize,
476 pub offset: usize,
477}
478
479impl Position {
480 pub const fn new(block: usize, offset: usize) -> Self {
481 Self { block, offset }
482 }
483}
484
485#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
487pub struct Selection {
488 pub anchor: Position,
490 pub head: Position,
492}
493
494impl Selection {
495 pub const fn caret(at: Position) -> Self {
496 Self {
497 anchor: at,
498 head: at,
499 }
500 }
501
502 pub const fn new(anchor: Position, head: Position) -> Self {
503 Self { anchor, head }
504 }
505
506 pub fn start(&self) -> Position {
507 self.anchor.min(self.head)
508 }
509
510 pub fn end(&self) -> Position {
511 self.anchor.max(self.head)
512 }
513
514 pub fn is_collapsed(&self) -> bool {
515 self.anchor == self.head
516 }
517}
518
519#[derive(Debug, Clone, PartialEq, Eq)]
521pub struct Document {
522 blocks: Vec<Block>,
523}
524
525impl Default for Document {
526 fn default() -> Self {
527 Self::new()
528 }
529}
530
531impl Document {
532 pub fn new() -> Self {
534 Self {
535 blocks: vec![Block::default()],
536 }
537 }
538
539 pub fn from_blocks(blocks: impl IntoIterator<Item = Block>) -> Self {
540 let blocks: Vec<Block> = blocks.into_iter().collect();
541 if blocks.is_empty() {
542 return Self::new();
543 }
544 Self { blocks }
545 }
546
547 pub fn from_text(text: &str) -> Self {
549 Self::from_blocks(
550 text.split('\n')
551 .map(|line| Block::paragraph(line.strip_suffix('\r').unwrap_or(line))),
552 )
553 }
554
555 pub fn blocks(&self) -> &[Block] {
556 &self.blocks
557 }
558
559 pub fn block(&self, index: usize) -> Option<&Block> {
560 self.blocks.get(index)
561 }
562
563 pub fn text(&self) -> String {
565 self.blocks
566 .iter()
567 .map(Block::text)
568 .collect::<Vec<_>>()
569 .join("\n")
570 }
571
572 pub fn is_empty(&self) -> bool {
574 matches!(self.blocks.as_slice(), [block] if block.is_empty() && block.kind == BlockKind::Paragraph)
575 }
576
577 pub fn has_formatting(&self) -> bool {
580 self.blocks.iter().any(|block| {
581 block.kind != BlockKind::Paragraph
582 || block
583 .runs
584 .iter()
585 .any(|run| !run.text.is_empty() && !run.style.is_plain())
586 })
587 }
588
589 pub fn start(&self) -> Position {
590 Position::default()
591 }
592
593 pub fn end(&self) -> Position {
594 let block = self.blocks.len().saturating_sub(1);
595 Position::new(block, self.blocks.get(block).map_or(0, Block::len))
596 }
597
598 pub fn clamp(&self, at: Position) -> Position {
600 let Some(block) = self.blocks.get(at.block) else {
601 return self.end();
602 };
603 let text = block.text();
604 let mut offset = at.offset.min(text.len());
605 while !text.is_char_boundary(offset) {
606 offset -= 1;
607 }
608 Position::new(at.block, offset)
609 }
610
611 pub fn number(&self, block: usize) -> Option<usize> {
614 if self.blocks.get(block)?.kind != BlockKind::Numbered {
615 return None;
616 }
617 let above = self.blocks[..block]
618 .iter()
619 .rev()
620 .take_while(|block| block.kind == BlockKind::Numbered)
621 .count();
622 Some(above + 1)
623 }
624
625 pub fn style_for_insert(&self, at: Position) -> Style {
628 let Some(block) = self.blocks.get(at.block) else {
629 return Style::default();
630 };
631 let mut style = block.style_before(at.offset).clone();
632 let inside = at.offset > 0
633 && block
634 .style_after(at.offset)
635 .and_then(|after| after.link.as_ref())
636 == style.link.as_ref();
637 if !inside {
638 style.link = None;
639 }
640 style
641 }
642
643 pub fn slice(&self, start: Position, end: Position) -> Document {
645 let (start, end) = (start.min(end), start.max(end));
646 let mut blocks = Vec::new();
647 let range = self.blocks.iter().enumerate().take(end.block + 1);
648 for (index, block) in range.skip(start.block) {
649 let from = if index == start.block {
650 start.offset
651 } else {
652 0
653 };
654 let to = if index == end.block {
655 end.offset
656 } else {
657 block.len()
658 };
659 blocks.push(Block::with_runs(block.kind, block.slice(from, to)));
660 }
661 Self::from_blocks(blocks)
662 }
663
664 pub fn delete(&mut self, start: Position, end: Position) -> Position {
667 let (start, end) = (self.clamp(start.min(end)), self.clamp(start.max(end)));
668 if start == end {
669 return start;
670 }
671 if start.block == end.block {
672 self.blocks[start.block].remove(start.offset, end.offset);
673 return start;
674 }
675 let tail = self.blocks[end.block].split_off(end.offset);
676 let head = &mut self.blocks[start.block];
677 head.split_off(start.offset);
678 let at = head.len();
679 head.insert_runs(at, tail);
680 self.blocks.drain(start.block + 1..=end.block);
681 start
682 }
683
684 pub fn insert_text(&mut self, at: Position, text: &str, style: &Style) -> Position {
687 let lines = text.split('\n').map(|line| {
688 Block::with_runs(
689 BlockKind::Paragraph,
690 [Run::new(
691 line.strip_suffix('\r').unwrap_or(line),
692 style.clone(),
693 )],
694 )
695 });
696 self.insert(at, &Document::from_blocks(lines))
697 }
698
699 pub fn insert(&mut self, at: Position, fragment: &Document) -> Position {
703 let at = self.clamp(at);
704 let target = self.blocks[at.block].kind;
705 let pasted = |kind: BlockKind| {
706 if kind == BlockKind::Paragraph {
707 target
708 } else {
709 kind
710 }
711 };
712 let [first, rest @ ..] = fragment.blocks.as_slice() else {
713 return at;
714 };
715 let first_runs: Vec<Run> = first.runs.clone();
716 let Some((last, middle)) = rest.split_last() else {
717 let block = &mut self.blocks[at.block];
718 let before = block.len();
719 block.insert_runs(at.offset, first_runs);
720 return Position::new(at.block, at.offset + block.len() - before);
721 };
722 let block = &mut self.blocks[at.block];
723 if block.is_empty() && first.kind != BlockKind::Paragraph {
724 block.kind = first.kind;
725 }
726 let tail = block.split_off(at.offset);
727 let end = block.len();
728 block.insert_runs(end, first_runs);
729 let mut new_blocks: Vec<Block> = middle
730 .iter()
731 .map(|block| Block::with_runs(pasted(block.kind), block.runs.clone()))
732 .collect();
733 let mut closing = Block::with_runs(pasted(last.kind), last.runs.clone());
734 let offset = closing.len();
735 let closing_len = closing.len();
736 closing.insert_runs(closing_len, tail);
737 new_blocks.push(closing);
738 let index = at.block + new_blocks.len();
739 self.blocks.splice(at.block + 1..at.block + 1, new_blocks);
740 Position::new(index, offset)
741 }
742
743 pub fn split(&mut self, at: Position) -> Position {
746 let at = self.clamp(at);
747 let block = &mut self.blocks[at.block];
748 let tail = block.split_off(at.offset);
749 let next = Block::with_runs(block.kind, tail);
750 self.blocks.insert(at.block + 1, next);
751 Position::new(at.block + 1, 0)
752 }
753
754 pub fn restyle(&mut self, start: Position, end: Position, change: impl Fn(&mut Style)) {
757 let (start, end) = (self.clamp(start.min(end)), self.clamp(start.max(end)));
758 let range = self.blocks.iter_mut().enumerate().take(end.block + 1);
759 for (index, block) in range.skip(start.block) {
760 let from = if index == start.block {
761 start.offset
762 } else {
763 0
764 };
765 let to = if index == end.block {
766 end.offset
767 } else {
768 block.len()
769 };
770 if from < to || block.is_empty() {
771 block.restyle(from, to, &change);
772 }
773 }
774 }
775
776 pub fn set_kind(&mut self, first: usize, last: usize, kind: BlockKind) {
778 for block in self.blocks.iter_mut().take(last + 1).skip(first) {
779 block.kind = kind;
780 }
781 }
782
783 pub fn all_have(&self, start: Position, end: Position, test: impl Fn(&Style) -> bool) -> bool {
786 let (start, end) = (start.min(end), start.max(end));
787 if start == end {
788 return test(&self.style_for_insert(start));
789 }
790 let mut any = false;
791 for (style, _) in self.styles_between(start, end) {
792 any = true;
793 if !test(style) {
794 return false;
795 }
796 }
797 any || test(&self.style_for_insert(start))
798 }
799
800 fn styles_between(&self, start: Position, end: Position) -> Vec<(&Style, usize)> {
803 let mut styles = Vec::new();
804 let range = self.blocks.iter().enumerate().take(end.block + 1);
805 for (index, block) in range.skip(start.block) {
806 let from = if index == start.block {
807 start.offset
808 } else {
809 0
810 };
811 let to = if index == end.block {
812 end.offset
813 } else {
814 block.len()
815 };
816 let mut at = 0;
817 for run in &block.runs {
818 let run_end = at + run.text.len();
819 let overlap = to.min(run_end).saturating_sub(from.max(at));
820 if overlap > 0 {
821 styles.push((&run.style, overlap));
822 }
823 at = run_end;
824 }
825 }
826 styles
827 }
828
829 pub fn size_between(&self, start: Position, end: Position) -> Option<Size> {
831 let (start, end) = (start.min(end), start.max(end));
832 if start == end {
833 return Some(self.style_for_insert(start).size);
834 }
835 let styles = self.styles_between(start, end);
836 let first = styles.first().map(|(style, _)| style.size)?;
837 styles
838 .iter()
839 .all(|(style, _)| style.size == first)
840 .then_some(first)
841 }
842
843 pub fn link_at(&self, at: Position) -> Option<(Position, Position, Arc<str>)> {
845 let block = self.blocks.get(at.block)?;
846 let (start, end, link) = block.link_range(at.offset)?;
847 Some((
848 Position::new(at.block, start),
849 Position::new(at.block, end),
850 link,
851 ))
852 }
853
854 pub fn previous(&self, at: Position) -> Position {
857 let at = self.clamp(at);
858 let block = &self.blocks[at.block];
859 if at.offset == 0 {
860 if at.block == 0 {
861 return at;
862 }
863 return Position::new(at.block - 1, self.blocks[at.block - 1].len());
864 }
865 let text = block.text();
866 let offset = block.previous_boundary(&text, at.offset).unwrap_or(0);
867 Position::new(at.block, offset)
868 }
869
870 pub fn next(&self, at: Position) -> Position {
873 let at = self.clamp(at);
874 let block = &self.blocks[at.block];
875 if at.offset >= block.len() {
876 if at.block + 1 >= self.blocks.len() {
877 return at;
878 }
879 return Position::new(at.block + 1, 0);
880 }
881 let text = block.text();
882 let offset = block.next_boundary(&text, at.offset).unwrap_or(text.len());
883 Position::new(at.block, offset)
884 }
885
886 pub fn word_left(&self, at: Position) -> Position {
888 let at = self.clamp(at);
889 if at.offset == 0 {
890 return self.previous(at);
891 }
892 let text = self.blocks[at.block].text();
893 let head = &text[..at.offset];
894 let start = head
895 .split_word_bound_indices()
896 .rev()
897 .find(|(_, word)| !word.trim().is_empty())
898 .map_or(0, |(start, _)| start);
899 Position::new(at.block, start)
900 }
901
902 pub fn word_right(&self, at: Position) -> Position {
904 let at = self.clamp(at);
905 let text = self.blocks[at.block].text();
906 if at.offset >= text.len() {
907 return self.next(at);
908 }
909 let end = text[at.offset..]
910 .split_word_bound_indices()
911 .find(|(_, word)| !word.trim().is_empty())
912 .map_or(text.len(), |(start, word)| at.offset + start + word.len());
913 Position::new(at.block, end)
914 }
915
916 pub fn word_at(&self, at: Position) -> (Position, Position) {
918 let at = self.clamp(at);
919 let text = self.blocks[at.block].text();
920 let mut found = None;
921 for (start, word) in text.split_word_bound_indices() {
922 let end = start + word.len();
923 if start <= at.offset && at.offset < end {
924 found = Some((start, end));
925 break;
926 }
927 if end == at.offset {
928 found = Some((start, end));
929 }
930 }
931 let (start, end) = found.unwrap_or((at.offset, at.offset));
932 (Position::new(at.block, start), Position::new(at.block, end))
933 }
934
935 pub fn word_touching(&self, at: Position) -> Option<(Position, Position)> {
937 let at = self.clamp(at);
938 let text = self.blocks.get(at.block)?.text();
939 let mut found = None;
940 for (start, word) in text.split_word_bound_indices() {
941 let end = start + word.len();
942 if start > at.offset {
943 break;
944 }
945 if at.offset <= end && word.chars().any(char::is_alphanumeric) {
946 found = Some((start, end));
947 if at.offset < end {
948 break;
949 }
950 }
951 }
952 let (start, end) = found?;
953 Some((Position::new(at.block, start), Position::new(at.block, end)))
954 }
955}
956
957pub fn normalise_link(address: &str) -> Option<String> {
961 let address = address.trim();
962 if address.is_empty()
963 || address
964 .chars()
965 .any(|c| c.is_whitespace() || c.is_control() || matches!(c, '<' | '>' | '"'))
966 {
967 return None;
968 }
969 let lower = address.to_ascii_lowercase();
970 for scheme in ["https://", "http://", "mailto:"] {
971 if lower.starts_with(scheme) {
972 return (address.len() > scheme.len()).then(|| address.to_owned());
973 }
974 }
975 if lower.contains("://") {
976 return None;
977 }
978 if let Some((_, rest)) = lower.split_once(':')
981 && !rest.starts_with(|c: char| c.is_ascii_digit())
982 {
983 return None;
984 }
985 if address.contains('@') && !address.contains('/') {
986 return Some(format!("mailto:{address}"));
987 }
988 let host = address.split(['/', '?', '#']).next().unwrap_or_default();
990 if !host.contains(['.', ':']) {
991 return None;
992 }
993 Some(format!("https://{address}"))
994}
995
996#[cfg(test)]
997mod tests {
998 use super::*;
999
1000 fn bold() -> Style {
1001 Style::default().with(Mark::Bold)
1002 }
1003
1004 fn doc(lines: &[&str]) -> Document {
1005 Document::from_text(&lines.join("\n"))
1006 }
1007
1008 fn at(block: usize, offset: usize) -> Position {
1009 Position::new(block, offset)
1010 }
1011
1012 #[test]
1013 fn a_new_document_is_one_empty_paragraph() {
1014 let document = Document::new();
1015 assert!(document.is_empty());
1016 assert_eq!(document.blocks().len(), 1);
1017 assert_eq!(document.text(), "");
1018 assert!(!document.has_formatting());
1019 assert_eq!(Document::from_blocks([]), document);
1020 }
1021
1022 #[test]
1023 fn runs_of_the_same_style_merge_and_empty_runs_go() {
1024 let block = Block::with_runs(
1025 BlockKind::Paragraph,
1026 [
1027 Run::plain("a"),
1028 Run::plain("b"),
1029 Run::new("", bold()),
1030 Run::new("c", bold()),
1031 ],
1032 );
1033 assert_eq!(block.runs(), [Run::plain("ab"), Run::new("c", bold())]);
1034 let empty = Block::with_runs(BlockKind::Bullet, [Run::new("", bold())]);
1035 assert_eq!(empty.runs(), [Run::new("", bold())]);
1036 assert!(empty.is_empty());
1037 }
1038
1039 #[test]
1040 fn styling_part_of_a_word_splits_its_run() {
1041 let mut document = doc(&["hello"]);
1042 document.restyle(at(0, 1), at(0, 3), |style| style.bold = true);
1043 assert_eq!(
1044 document.blocks()[0].runs(),
1045 [Run::plain("h"), Run::new("el", bold()), Run::plain("lo")]
1046 );
1047 document.restyle(at(0, 0), at(0, 5), |style| style.bold = true);
1048 assert_eq!(document.blocks()[0].runs(), [Run::new("hello", bold())]);
1049 }
1050
1051 #[test]
1052 fn restyling_across_blocks_touches_each() {
1053 let mut document = doc(&["one", "two", "three"]);
1054 document.restyle(at(0, 1), at(2, 2), |style| style.italic = true);
1055 let italic = Style::default().with(Mark::Italic);
1056 assert_eq!(
1057 document.blocks()[0].runs(),
1058 [Run::plain("o"), Run::new("ne", italic.clone())]
1059 );
1060 assert_eq!(
1061 document.blocks()[1].runs(),
1062 [Run::new("two", italic.clone())]
1063 );
1064 assert_eq!(
1065 document.blocks()[2].runs(),
1066 [Run::new("th", italic), Run::plain("ree")]
1067 );
1068 }
1069
1070 #[test]
1071 fn deleting_within_and_across_blocks() {
1072 let mut document = doc(&["hello", "world"]);
1073 assert_eq!(document.delete(at(0, 1), at(0, 3)), at(0, 1));
1074 assert_eq!(document.text(), "hlo\nworld");
1075 assert_eq!(document.delete(at(1, 2), at(0, 2)), at(0, 2));
1076 assert_eq!(document.text(), "hlrld");
1077 assert_eq!(document.blocks().len(), 1);
1078 }
1079
1080 #[test]
1081 fn deleting_everything_keeps_the_style_for_typing() {
1082 let mut document = Document::from_blocks([Block::with_runs(
1083 BlockKind::Paragraph,
1084 [Run::new("bold", bold())],
1085 )]);
1086 document.delete(at(0, 0), at(0, 4));
1087 assert_eq!(document.blocks()[0].runs(), [Run::new("", bold())]);
1088 assert_eq!(document.style_for_insert(at(0, 0)), bold());
1089 }
1090
1091 #[test]
1092 fn inserting_text_with_line_breaks_makes_blocks() {
1093 let mut document = doc(&["ab"]);
1094 let end = document.insert_text(at(0, 1), "1\n2\n3", &bold());
1095 assert_eq!(end, at(2, 1));
1096 assert_eq!(document.text(), "a1\n2\n3b");
1097 assert_eq!(
1098 document.blocks()[0].runs(),
1099 [Run::plain("a"), Run::new("1", bold())]
1100 );
1101 assert_eq!(
1102 document.blocks()[2].runs(),
1103 [Run::new("3", bold()), Run::plain("b")]
1104 );
1105 }
1106
1107 #[test]
1108 fn pasted_paragraphs_join_the_list_they_land_in() {
1109 let mut document =
1110 Document::from_blocks([Block::with_runs(BlockKind::Bullet, [Run::plain("item")])]);
1111 document.insert_text(at(0, 4), "\nnext\nlast", &Style::default());
1112 let kinds: Vec<_> = document.blocks().iter().map(Block::kind).collect();
1113 assert_eq!(kinds, [BlockKind::Bullet; 3]);
1114 }
1115
1116 #[test]
1117 fn splitting_keeps_the_kind_and_the_style() {
1118 let mut document = Document::from_blocks([Block::with_runs(
1119 BlockKind::Numbered,
1120 [Run::new("onetwo", bold())],
1121 )]);
1122 assert_eq!(document.split(at(0, 3)), at(1, 0));
1123 assert_eq!(document.blocks()[1].kind(), BlockKind::Numbered);
1124 assert_eq!(document.blocks()[1].runs(), [Run::new("two", bold())]);
1125 assert_eq!(document.split(at(1, 3)), at(2, 0));
1126 assert_eq!(document.blocks()[2].runs(), [Run::new("", bold())]);
1127 assert_eq!(document.number(2), Some(3));
1128 }
1129
1130 #[test]
1131 fn slices_cut_runs_at_both_ends() {
1132 let mut document = doc(&["hello", "there"]);
1133 document.restyle(at(0, 0), at(0, 2), |style| style.bold = true);
1134 let slice = document.slice(at(0, 1), at(1, 2));
1135 assert_eq!(slice.text(), "ello\nth");
1136 assert_eq!(
1137 slice.blocks()[0].runs(),
1138 [Run::new("e", bold()), Run::plain("llo")]
1139 );
1140 }
1141
1142 #[test]
1143 fn numbers_count_the_items_above() {
1144 let mut document = doc(&["a", "b", "c", "d"]);
1145 document.set_kind(0, 1, BlockKind::Numbered);
1146 document.set_kind(3, 3, BlockKind::Numbered);
1147 assert_eq!(document.number(0), Some(1));
1148 assert_eq!(document.number(1), Some(2));
1149 assert_eq!(document.number(2), None);
1150 assert_eq!(document.number(3), Some(1));
1151 }
1152
1153 #[test]
1154 fn typing_after_a_link_does_not_extend_it() {
1155 let link = Style::default().linked("https://example.com");
1156 let document = Document::from_blocks([Block::with_runs(
1157 BlockKind::Paragraph,
1158 [
1159 Run::plain("see "),
1160 Run::new("here", link.clone()),
1161 Run::plain("."),
1162 ],
1163 )]);
1164 assert_eq!(document.style_for_insert(at(0, 6)).link, link.link);
1165 assert_eq!(document.style_for_insert(at(0, 8)).link, None);
1166 assert_eq!(document.style_for_insert(at(0, 4)).link, None);
1167 let (start, end, url) = document.link_at(at(0, 8)).unwrap();
1168 assert_eq!(
1169 (start, end, &*url),
1170 (at(0, 4), at(0, 8), "https://example.com")
1171 );
1172 assert!(document.link_at(at(0, 2)).is_none());
1173 }
1174
1175 #[test]
1176 fn graphemes_move_as_one() {
1177 let document = doc(&["e\u{301}x", "y"]);
1178 assert_eq!(document.next(at(0, 0)), at(0, 3));
1179 assert_eq!(document.previous(at(0, 3)), at(0, 0));
1180 assert_eq!(document.next(at(0, 4)), at(1, 0));
1181 assert_eq!(document.previous(at(1, 0)), at(0, 4));
1182 assert_eq!(document.previous(at(0, 0)), at(0, 0));
1183 assert_eq!(document.next(at(1, 1)), at(1, 1));
1184 }
1185
1186 #[test]
1187 fn words_move_and_select() {
1188 let document = doc(&["one two three", "four"]);
1189 assert_eq!(document.word_left(at(0, 9)), at(0, 4));
1190 assert_eq!(document.word_left(at(0, 4)), at(0, 0));
1191 assert_eq!(document.word_left(at(1, 0)), at(0, 14));
1192 assert_eq!(document.word_right(at(0, 0)), at(0, 3));
1193 assert_eq!(document.word_right(at(0, 3)), at(0, 7));
1194 assert_eq!(document.word_right(at(0, 14)), at(1, 0));
1195 assert_eq!(document.word_at(at(0, 5)), (at(0, 4), at(0, 7)));
1196 assert_eq!(document.word_at(at(0, 7)), (at(0, 7), at(0, 9)));
1197 assert_eq!(document.word_touching(at(0, 7)), Some((at(0, 4), at(0, 7))));
1198 assert_eq!(document.word_touching(at(0, 8)), None);
1199 }
1200
1201 #[test]
1202 fn marks_and_sizes_across_a_range() {
1203 let mut document = doc(&["abcd"]);
1204 document.restyle(at(0, 0), at(0, 2), |style| style.bold = true);
1205 assert!(document.all_have(at(0, 0), at(0, 2), |s| s.bold));
1206 assert!(!document.all_have(at(0, 0), at(0, 3), |s| s.bold));
1207 assert!(document.all_have(at(0, 1), at(0, 1), |s| s.bold));
1208 assert_eq!(
1209 document.size_between(at(0, 0), at(0, 4)),
1210 Some(Size::Normal)
1211 );
1212 document.restyle(at(0, 3), at(0, 4), |style| style.size = Size::Huge);
1213 assert_eq!(document.size_between(at(0, 0), at(0, 4)), None);
1214 assert_eq!(document.size_between(at(0, 3), at(0, 4)), Some(Size::Huge));
1215 }
1216
1217 #[test]
1218 fn clamping_keeps_positions_on_characters() {
1219 let document = doc(&["añb"]);
1220 assert_eq!(document.clamp(at(0, 2)), at(0, 1));
1221 assert_eq!(document.clamp(at(0, 99)), at(0, 4));
1222 assert_eq!(document.clamp(at(5, 0)), at(0, 4));
1223 }
1224
1225 #[test]
1226 fn has_formatting_notices_styles_and_lists() {
1227 let mut document = doc(&["plain"]);
1228 assert!(!document.has_formatting());
1229 document.set_kind(0, 0, BlockKind::Bullet);
1230 assert!(document.has_formatting());
1231 let mut styled = doc(&["x"]);
1232 styled.restyle(at(0, 0), at(0, 1), |style| style.size = Size::Large);
1233 assert!(styled.has_formatting());
1234 }
1235
1236 #[test]
1237 fn links_are_made_safe() {
1238 assert_eq!(
1239 normalise_link("example.com").as_deref(),
1240 Some("https://example.com")
1241 );
1242 assert_eq!(
1243 normalise_link(" https://a.b/c?d=1 ").as_deref(),
1244 Some("https://a.b/c?d=1")
1245 );
1246 assert_eq!(normalise_link("HTTP://a.b").as_deref(), Some("HTTP://a.b"));
1247 assert_eq!(
1248 normalise_link("sam@example.com").as_deref(),
1249 Some("mailto:sam@example.com")
1250 );
1251 assert_eq!(
1252 normalise_link("mailto:sam@example.com").as_deref(),
1253 Some("mailto:sam@example.com")
1254 );
1255 assert_eq!(
1256 normalise_link("localhost:8080").as_deref(),
1257 Some("https://localhost:8080")
1258 );
1259 assert_eq!(normalise_link("javascript:alert(1)"), None);
1260 assert_eq!(normalise_link("data:text/html,x"), None);
1261 assert_eq!(normalise_link("https://"), None);
1262 assert_eq!(normalise_link("a b"), None);
1263 assert_eq!(normalise_link("abc"), None);
1264 assert_eq!(normalise_link("abc/x.html"), None);
1265 assert_eq!(normalise_link(""), None);
1266 }
1267
1268 #[test]
1269 fn size_codes_round_trip() {
1270 for size in Size::ALL {
1271 assert_eq!(Size::from_code(size.code()), size);
1272 }
1273 for kind in [
1274 BlockKind::Paragraph,
1275 BlockKind::Bullet,
1276 BlockKind::Numbered,
1277 BlockKind::Quote,
1278 ] {
1279 assert_eq!(BlockKind::from_code(kind.code()), kind);
1280 }
1281 }
1282}