1use crate::{Color, Font, FontSpec, FontWeight, TextRun, runs_are_valid};
18
19#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
29pub enum Underline {
30 #[default]
31 None,
32 Single,
33 Double,
34 Dotted,
35 Wavy,
37}
38
39impl Underline {
40 #[must_use]
41 pub fn is_on(self) -> bool {
42 self != Underline::None
43 }
44 #[must_use]
46 pub fn toggled(self) -> Self {
47 if self.is_on() {
48 Underline::None
49 } else {
50 Underline::Single
51 }
52 }
53}
54
55#[derive(Clone, Debug, Default, PartialEq)]
58pub struct RunStyle {
59 pub font: FontSpec,
60 pub color: Option<Color>,
61 pub background: Option<Color>,
62 pub underline: Underline,
63 pub strikethrough: bool,
64 pub link: Option<String>,
65}
66
67impl RunStyle {
68 #[must_use]
70 pub fn plain(base: Font) -> Self {
71 RunStyle {
72 font: FontSpec::new(base),
73 ..RunStyle::default()
74 }
75 }
76 #[must_use]
78 pub fn bold(&self) -> bool {
79 self.font.weight.is_some_and(|w| w >= FontWeight::Semibold)
80 }
81 pub fn set_bold(&mut self, on: bool) {
82 self.font.weight = on.then_some(FontWeight::Bold);
83 }
84 #[must_use]
85 pub fn italic(&self) -> bool {
86 self.font.italic
87 }
88 pub fn set_italic(&mut self, on: bool) {
89 self.font.italic = on;
90 }
91}
92
93#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
99pub enum ParagraphAlign {
100 #[default]
102 Natural,
103 Center,
104 Trailing,
106 Justified,
107}
108
109#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
111pub enum ListStyle {
112 #[default]
113 None,
114 Bullet,
116 Ordered(u32),
119}
120
121#[derive(Clone, Copy, Debug, Default, PartialEq)]
123pub struct ParagraphStyle {
124 pub align: ParagraphAlign,
125 pub indent: f64,
128 pub space_before: f64,
129 pub space_after: f64,
130 pub list: ListStyle,
131 pub list_level: u8,
133}
134
135#[derive(Clone, Debug, Default, PartialEq)]
145pub struct ParagraphRun {
146 pub range: std::ops::Range<usize>,
147 pub align: ParagraphAlign,
148 pub indent: f64,
149 pub space_before: f64,
150 pub space_after: f64,
151 pub list: ListStyle,
152 pub list_level: u8,
153}
154
155impl ParagraphRun {
156 #[must_use]
157 pub fn new(range: std::ops::Range<usize>, style: ParagraphStyle) -> Self {
158 ParagraphRun {
159 range,
160 align: style.align,
161 indent: style.indent,
162 space_before: style.space_before,
163 space_after: style.space_after,
164 list: style.list,
165 list_level: style.list_level,
166 }
167 }
168 #[must_use]
169 pub fn style(&self) -> ParagraphStyle {
170 ParagraphStyle {
171 align: self.align,
172 indent: self.indent,
173 space_before: self.space_before,
174 space_after: self.space_after,
175 list: self.list,
176 list_level: self.list_level,
177 }
178 }
179}
180
181#[derive(Clone, Debug, Default, PartialEq)]
188pub struct StyledText {
189 pub text: String,
190 pub runs: Vec<TextRun>,
191 pub paragraphs: Vec<ParagraphRun>,
192}
193
194impl From<String> for StyledText {
195 fn from(text: String) -> Self {
196 StyledText::plain(text)
197 }
198}
199
200impl From<&str> for StyledText {
201 fn from(text: &str) -> Self {
202 StyledText::plain(text)
203 }
204}
205
206impl StyledText {
207 pub fn plain(text: impl Into<String>) -> Self {
209 StyledText {
210 text: text.into(),
211 runs: Vec::new(),
212 paragraphs: Vec::new(),
213 }
214 }
215
216 #[must_use]
219 pub fn markdown(md: &str, base: Font) -> Self {
220 crate::styled_codec::markdown_to_styled(
221 md,
222 crate::styled_codec::DocStyle {
223 base,
224 ..Default::default()
225 },
226 )
227 }
228
229 #[must_use]
231 pub fn html(html: &str, base: Font) -> Self {
232 crate::styled_codec::html_to_styled(
233 html,
234 crate::styled_codec::DocStyle {
235 base,
236 ..Default::default()
237 },
238 )
239 }
240
241 #[must_use]
243 pub fn rtf(rtf: &str, base: Font) -> Self {
244 crate::styled_codec::rtf_to_styled(
245 rtf,
246 crate::styled_codec::DocStyle {
247 base,
248 ..Default::default()
249 },
250 )
251 }
252
253 #[must_use]
256 pub fn to_markdown(&self, base: Font) -> String {
257 crate::styled_codec::styled_to_markdown(
258 self,
259 crate::styled_codec::DocStyle {
260 base,
261 ..Default::default()
262 },
263 )
264 }
265
266 #[must_use]
267 pub fn to_html(&self, base: Font) -> String {
268 crate::styled_codec::styled_to_html(
269 self,
270 crate::styled_codec::DocStyle {
271 base,
272 ..Default::default()
273 },
274 )
275 }
276
277 #[must_use]
278 pub fn to_rtf(&self, base: Font) -> String {
279 crate::styled_codec::styled_to_rtf(
280 self,
281 crate::styled_codec::DocStyle {
282 base,
283 ..Default::default()
284 },
285 )
286 }
287
288 pub fn new(text: impl Into<String>, runs: Vec<TextRun>) -> Self {
290 StyledText {
291 text: text.into(),
292 runs,
293 paragraphs: Vec::new(),
294 }
295 }
296
297 #[must_use]
298 pub fn is_empty(&self) -> bool {
299 self.text.is_empty()
300 }
301
302 pub fn validate(&self) -> Result<(), String> {
309 runs_are_valid(&self.text, &self.runs)?;
310 paragraphs_are_valid(&self.text, &self.paragraphs)
311 }
312
313 #[must_use]
318 pub fn segments(&self, base: Font) -> Vec<(std::ops::Range<usize>, RunStyle)> {
319 let plain = RunStyle::plain(base);
320 let mut out = Vec::with_capacity(self.runs.len() * 2 + 1);
321 let mut at = 0usize;
322 for r in &self.runs {
323 if r.range.start > at {
324 out.push((at..r.range.start, plain.clone()));
325 }
326 if !r.range.is_empty() {
327 out.push((r.range.clone(), r.style()));
328 }
329 at = at.max(r.range.end);
330 }
331 if at < self.text.len() {
332 out.push((at..self.text.len(), plain));
333 }
334 out
335 }
336
337 #[must_use]
347 pub fn style_of(&self, range: std::ops::Range<usize>, base: Font) -> RunStyle {
348 let segs = self.segments(base);
349 if range.is_empty() {
350 let at = range.start;
351 return segs
352 .iter()
353 .find(|(r, _)| r.start < at && r.end >= at)
354 .or_else(|| segs.iter().find(|(r, _)| r.contains(&at)))
355 .map_or_else(|| RunStyle::plain(base), |(_, s)| s.clone());
356 }
357 let mut acc: Option<RunStyle> = None;
358 for (r, s) in &segs {
359 if r.end <= range.start || r.start >= range.end {
360 continue;
361 }
362 acc = Some(merge_style(acc, s));
363 }
364 acc.unwrap_or_else(|| RunStyle::plain(base))
365 }
366
367 pub fn apply(&mut self, range: std::ops::Range<usize>, base: Font, f: impl Fn(&mut RunStyle)) {
370 if range.start >= range.end || range.start >= self.text.len() {
371 return;
372 }
373 let range = range.start..range.end.min(self.text.len());
374 let mut out: Vec<TextRun> = Vec::new();
375 for (r, s) in self.segments(base) {
376 for (piece, inside) in [
378 (r.start..r.end.min(range.start), false),
379 (r.start.max(range.start)..r.end.min(range.end), true),
380 (r.start.max(range.end)..r.end, false),
381 ] {
382 if piece.start >= piece.end {
383 continue;
384 }
385 let mut style = s.clone();
386 if inside {
387 f(&mut style);
388 }
389 out.push(TextRun::styled(piece, style));
390 }
391 }
392 self.runs = coalesce_runs(out, base);
393 }
394
395 #[must_use]
398 pub fn paragraph_style_of(&self, range: std::ops::Range<usize>) -> ParagraphStyle {
399 let mut acc: Option<ParagraphStyle> = None;
400 for (start, end) in paragraph_bounds(&self.text) {
401 if !touches(start, end, &range) {
402 continue;
403 }
404 let style = self.paragraph_at(start, end);
405 acc = Some(match acc {
406 None => style,
407 Some(a) if a == style => a,
408 Some(_) => ParagraphStyle::default(),
409 });
410 }
411 acc.unwrap_or_default()
412 }
413
414 pub fn apply_paragraph(
417 &mut self,
418 range: std::ops::Range<usize>,
419 f: impl Fn(&mut ParagraphStyle),
420 ) {
421 let mut out: Vec<ParagraphRun> = Vec::new();
422 for (start, end) in paragraph_bounds(&self.text) {
423 let mut style = self.paragraph_at(start, end);
424 if touches(start, end, &range) {
425 f(&mut style);
426 }
427 if style != ParagraphStyle::default() {
428 out.push(ParagraphRun::new(start..end, style));
429 }
430 }
431 self.paragraphs = out;
432 }
433
434 fn paragraph_at(&self, start: usize, end: usize) -> ParagraphStyle {
436 self.paragraphs
437 .iter()
438 .find(|p| p.range.start <= start && p.range.end >= end.min(p.range.end).max(start + 1))
439 .map_or_default(ParagraphRun::style)
440 }
441
442 pub fn reflow(&mut self, offset: usize, removed: usize, inserted: usize) {
452 let shift = |p: usize| -> usize {
453 if p <= offset {
454 p
455 } else if p >= offset + removed {
456 p - removed + inserted
457 } else {
458 offset }
460 };
461 for r in &mut self.runs {
462 r.range = shift(r.range.start)..shift(r.range.end);
463 }
464 for p in &mut self.paragraphs {
465 p.range = shift(p.range.start)..shift(p.range.end);
466 }
467 if inserted > 0 {
470 for r in &mut self.runs {
471 if r.range.end == offset && r.range.start < offset {
472 r.range.end = offset + inserted;
473 }
474 }
475 for p in &mut self.paragraphs {
476 if p.range.end == offset && p.range.start < offset {
477 p.range.end = offset + inserted;
478 }
479 }
480 }
481 self.clamp();
482 }
483
484 pub fn clamp(&mut self) {
487 let text = std::mem::take(&mut self.text);
488 let fix = |p: usize| -> usize {
489 let mut p = p.min(text.len());
490 while p > 0 && !text.is_char_boundary(p) {
491 p -= 1;
492 }
493 p
494 };
495 for r in &mut self.runs {
496 r.range = fix(r.range.start)..fix(r.range.end);
497 }
498 for p in &mut self.paragraphs {
499 p.range = fix(p.range.start)..fix(p.range.end);
500 }
501 self.text = text;
502 self.runs.retain(|r| r.range.start < r.range.end);
503 self.paragraphs.retain(|p| p.range.start < p.range.end);
504 }
505
506 pub fn splice(&mut self, range: std::ops::Range<usize>, text: &str) {
509 let range = range.start.min(self.text.len())..range.end.min(self.text.len());
510 if !self.text.is_char_boundary(range.start) || !self.text.is_char_boundary(range.end) {
511 return;
512 }
513 let removed = range.end.saturating_sub(range.start);
514 self.text.replace_range(range.clone(), text);
515 self.reflow(range.start, removed, text.len());
516 }
517}
518
519#[expect(
522 clippy::float_cmp,
523 reason = "a merged run keeps a scale only when both runs store the identical value"
524)]
525fn merge_style(acc: Option<RunStyle>, b: &RunStyle) -> RunStyle {
526 let Some(a) = acc else { return b.clone() };
527 RunStyle {
528 font: FontSpec {
529 style: if a.font.style == b.font.style {
530 a.font.style
531 } else {
532 Font::Body
533 },
534 weight: if a.font.weight == b.font.weight {
535 a.font.weight
536 } else {
537 None
538 },
539 italic: a.font.italic && b.font.italic,
540 tabular: a.font.tabular && b.font.tabular,
541 monospace: a.font.monospace && b.font.monospace,
542 scale: if a.font.scale == b.font.scale {
543 a.font.scale
544 } else {
545 1.0
546 },
547 },
548 color: if a.color == b.color { a.color } else { None },
549 background: if a.background == b.background {
550 a.background
551 } else {
552 None
553 },
554 underline: if a.underline == b.underline {
555 a.underline
556 } else {
557 Underline::None
558 },
559 strikethrough: a.strikethrough && b.strikethrough,
560 link: if a.link == b.link { a.link } else { None },
561 }
562}
563
564fn touches(start: usize, end: usize, sel: &std::ops::Range<usize>) -> bool {
567 if sel.start == sel.end {
568 return sel.start >= start && sel.start <= end;
569 }
570 start < sel.end && end > sel.start
571}
572
573#[must_use]
578pub fn coalesce_runs(runs: Vec<TextRun>, base: Font) -> Vec<TextRun> {
579 let plain = RunStyle::plain(base);
580 let mut out: Vec<TextRun> = Vec::with_capacity(runs.len());
581 for r in runs {
582 if r.range.is_empty() {
583 continue;
584 }
585 match out.last_mut() {
586 Some(prev) if prev.range.end == r.range.start && prev.style() == r.style() => {
587 prev.range.end = r.range.end;
588 }
589 _ => out.push(r),
590 }
591 }
592 out.retain(|r| r.style() != plain);
593 out
594}
595
596#[must_use]
601pub fn paragraph_bounds(text: &str) -> Vec<(usize, usize)> {
602 if text.is_empty() {
603 return Vec::new();
604 }
605 let mut out = Vec::new();
606 let mut start = 0usize;
607 for (i, b) in text.bytes().enumerate() {
608 if b == b'\n' {
609 out.push((start, i + 1));
610 start = i + 1;
611 }
612 }
613 out.push((start, text.len()));
614 out
615}
616
617pub fn paragraphs_are_valid(text: &str, paragraphs: &[ParagraphRun]) -> Result<(), String> {
625 let mut prev_end = 0usize;
626 for (i, p) in paragraphs.iter().enumerate() {
627 if p.range.start < prev_end {
628 return Err(format!(
629 "paragraph {i} starts at {} but the previous ends at {prev_end} — paragraph runs \
630 must be ascending and non-overlapping",
631 p.range.start
632 ));
633 }
634 if p.range.end > text.len() {
635 return Err(format!(
636 "paragraph {i} ends at {} but the text is {} bytes",
637 p.range.end,
638 text.len()
639 ));
640 }
641 if p.range.start > p.range.end {
642 return Err(format!("paragraph {i} has an inverted range {:?}", p.range));
643 }
644 if !text.is_char_boundary(p.range.start) || !text.is_char_boundary(p.range.end) {
645 return Err(format!(
646 "paragraph {i}'s range {:?} splits a multi-byte character",
647 p.range
648 ));
649 }
650 prev_end = p.range.end;
651 }
652 Ok(())
653}
654
655#[cfg(test)]
656mod tests {
657 use super::*;
658
659 fn bold_run(range: std::ops::Range<usize>) -> TextRun {
660 TextRun::styled(range, {
661 let mut s = RunStyle::plain(Font::Body);
662 s.set_bold(true);
663 s
664 })
665 }
666
667 fn doc() -> StyledText {
668 StyledText::new("hello world", vec![bold_run(0..5)])
670 }
671
672 #[test]
673 fn segments_cover_the_whole_text_including_gaps() {
674 let segs = doc().segments(Font::Body);
675 assert_eq!(
676 segs.iter().map(|(r, _)| r.clone()).collect::<Vec<_>>(),
677 vec![0..5, 5..11]
678 );
679 assert!(segs[0].1.bold());
680 assert!(!segs[1].1.bold());
681 }
682
683 #[test]
684 fn style_of_a_uniform_selection_is_that_style() {
685 assert!(doc().style_of(0..5, Font::Body).bold());
686 assert!(!doc().style_of(5..11, Font::Body).bold());
687 }
688
689 #[test]
690 fn style_of_a_mixed_selection_resets_what_differs() {
691 let s = doc().style_of(0..11, Font::Body);
693 assert!(!s.bold(), "a mixed weight comes back as the default");
694 }
695
696 #[test]
697 fn a_caret_takes_the_style_of_the_run_it_ends() {
698 assert!(doc().style_of(5..5, Font::Body).bold());
700 assert!(!doc().style_of(11..11, Font::Body).bold());
702 assert!(doc().style_of(0..0, Font::Body).bold());
706 }
707
708 #[test]
709 fn apply_splits_runs_at_the_selection_boundaries() {
710 let mut d = doc();
711 d.apply(3..8, Font::Body, |s| s.set_italic(true));
712 let got: Vec<_> = d
714 .runs
715 .iter()
716 .map(|r| (r.range.clone(), r.style().bold(), r.style().italic()))
717 .collect();
718 assert_eq!(
719 got,
720 vec![(0..3, true, false), (3..5, true, true), (5..8, false, true),]
721 );
722 }
723
724 #[test]
725 fn apply_coalesces_and_drops_plain() {
726 let mut d = doc();
727 d.apply(0..11, Font::Body, |s| s.set_bold(false));
728 assert!(
729 d.runs.is_empty(),
730 "unbolding everything leaves nothing to say: {:?}",
731 d.runs
732 );
733 }
734
735 #[test]
736 fn reflow_moves_ranges_over_an_insert() {
737 let mut d = doc();
738 d.text = "hello woXXrld".into();
740 d.reflow(8, 0, 2);
741 assert_eq!(d.runs[0].range, 0..5, "a run before the edit is untouched");
742
743 let mut d = doc();
744 d.text = "heXXllo world".into();
746 d.reflow(2, 0, 2);
747 assert_eq!(d.runs[0].range, 0..7);
748 }
749
750 #[test]
751 fn typing_at_the_end_of_a_run_continues_it() {
752 let mut d = doc();
753 d.text = "helloX world".into();
754 d.reflow(5, 0, 1);
755 assert_eq!(d.runs[0].range, 0..6, "the bold run took the new character");
756 }
757
758 #[test]
759 fn reflow_shrinks_and_drops_over_a_delete() {
760 let mut d = doc();
761 d.text = "hworld".into();
763 d.reflow(1, 5, 0);
764 assert_eq!(d.runs[0].range, 0..1);
765
766 let mut d = doc();
767 d.text = " world".into();
769 d.reflow(0, 5, 0);
770 assert!(d.runs.is_empty(), "{:?}", d.runs);
771 }
772
773 #[test]
774 fn splice_edits_text_and_ranges_together() {
775 let mut d = doc();
776 d.splice(5..5, ",");
777 assert_eq!(d.text, "hello, world");
778 assert_eq!(d.runs[0].range, 0..6);
779 assert!(d.validate().is_ok());
780 }
781
782 #[test]
783 fn clamp_pulls_ranges_off_multi_byte_boundaries() {
784 let mut d = StyledText::new("héllo", vec![bold_run(0..2)]);
785 d.text = "h".into(); d.clamp();
787 assert!(d.validate().is_ok());
788 assert!(d.runs.iter().all(|r| r.range.end <= 1));
789 }
790
791 #[test]
792 fn paragraph_bounds_include_the_terminator_and_the_blank_last_line() {
793 assert_eq!(paragraph_bounds(""), Vec::new());
794 assert_eq!(paragraph_bounds("a"), vec![(0, 1)]);
795 assert_eq!(paragraph_bounds("a\n"), vec![(0, 2), (2, 2)]);
796 assert_eq!(paragraph_bounds("a\nbb\nc"), vec![(0, 2), (2, 5), (5, 6)]);
797 }
798
799 #[test]
800 fn apply_paragraph_styles_the_whole_paragraph_a_caret_sits_in() {
801 let mut d = StyledText::plain("one\ntwo\nthree");
802 d.apply_paragraph(5..5, |p| p.align = ParagraphAlign::Center);
803 assert_eq!(d.paragraphs.len(), 1);
804 assert_eq!(d.paragraphs[0].range, 4..8, "the whole second paragraph");
805 assert_eq!(d.paragraphs[0].align, ParagraphAlign::Center);
806 assert_eq!(d.paragraph_style_of(5..5).align, ParagraphAlign::Center);
807 assert_eq!(
808 d.paragraph_style_of(0..13).align,
809 ParagraphAlign::Natural,
810 "a mixed selection reports the default"
811 );
812 assert!(d.validate().is_ok());
813 }
814
815 #[test]
816 fn paragraph_ranges_reflow_with_the_text() {
817 let mut d = StyledText::plain("one\ntwo");
818 d.apply_paragraph(5..5, |p| p.list = ListStyle::Bullet);
819 assert_eq!(d.paragraphs[0].range, 4..7);
820 d.splice(0..0, "XY");
821 assert_eq!(d.paragraphs[0].range, 6..9);
822 assert!(d.validate().is_ok());
823 }
824
825 #[test]
826 fn font_scale_resolves_against_the_platforms_style_size() {
827 let s = FontSpec::new(Font::Body).scaled(1.5);
828 assert_eq!(s.resolved_points(16.0), 24.0);
829 let abs = FontSpec::new(Font::System(14.0));
831 assert_eq!(abs.resolved_points(16.0), 14.0);
832 assert_eq!(abs.scaled(2.0).resolved_points(16.0), 28.0);
833 }
834}