Skip to main content

mrk/
document.rs

1use std::ops::Range;
2use std::sync::Arc;
3use std::time::Instant;
4
5use crate::link::LinkBase;
6use crate::sanitize;
7use crate::theme::Theme;
8
9#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
10pub struct Rgb(pub u8, pub u8, pub u8);
11
12impl Rgb {
13    /// `#rrggbb`, as SVG and CSS write a colour.
14    pub(crate) fn hex(self) -> String {
15        format!("#{:02x}{:02x}{:02x}", self.0, self.1, self.2)
16    }
17
18    /// The colour `amount` of the way from this one to `other`: 0.0 keeps it, 1.0 gives `other`.
19    #[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss, reason = "a float `as u8` saturates into 0..=255")]
20    pub(crate) fn mix(self, other: Rgb, amount: f32) -> Rgb {
21        let channel = |from: u8, to: u8| (f32::from(from) + (f32::from(to) - f32::from(from)) * amount).round() as u8;
22        Rgb(channel(self.0, other.0), channel(self.1, other.1), channel(self.2, other.2))
23    }
24}
25
26#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
27#[non_exhaustive]
28pub struct Style {
29    pub fg: Option<Rgb>,
30    pub bg: Option<Rgb>,
31    pub bold: bool,
32    pub italic: bool,
33    pub underline: bool,
34    pub strike: bool,
35    pub dim: bool,
36}
37
38impl Style {
39    pub fn fg(color: Rgb) -> Self {
40        Self::default().with_fg(color)
41    }
42
43    pub fn with_fg(self, color: Rgb) -> Self {
44        Self { fg: Some(color), ..self }
45    }
46
47    pub fn on(self, color: Rgb) -> Self {
48        Self { bg: Some(color), ..self }
49    }
50
51    pub fn bold(self) -> Self {
52        Self { bold: true, ..self }
53    }
54
55    pub fn italic(self) -> Self {
56        Self { italic: true, ..self }
57    }
58
59    pub fn underline(self) -> Self {
60        Self { underline: true, ..self }
61    }
62
63    pub fn strike(self) -> Self {
64        Self { strike: true, ..self }
65    }
66
67    pub fn dim(self) -> Self {
68        Self { dim: true, ..self }
69    }
70}
71
72#[derive(Clone, Debug, Default, PartialEq, Eq)]
73#[non_exhaustive]
74pub struct Span {
75    pub text: String,
76    pub style: Style,
77    /// The target `sanitize::link` gives, shared by every span the link's text wraps into.
78    pub link: Option<Arc<str>>,
79    /// Drawn by mrk around the input's text (a bar, a border, a marker, padding), never written by the input: what a
80    /// diff leaves out.
81    pub is_frame: bool,
82}
83
84impl Span {
85    pub fn new(text: impl Into<String>, style: Style) -> Self {
86        Self { text: text.into(), style, link: None, is_frame: false }
87    }
88
89    pub fn plain(text: impl Into<String>) -> Self {
90        Self::new(text, Style::default())
91    }
92
93    pub fn linked(self, target: impl Into<Arc<str>>) -> Self {
94        Self { link: Some(target.into()), ..self }
95    }
96
97    pub fn framed(self) -> Self {
98        Self { is_frame: true, ..self }
99    }
100
101    /// The span's look and role, all but its text: what decides whether two neighbours can be one span.
102    fn looks_like(&self, other: &Span) -> bool {
103        self.style == other.style && self.link == other.link && self.is_frame == other.is_frame
104    }
105
106    /// This span with its look and role but no text, to build a span of the same kind from.
107    fn without_text(&self) -> Self {
108        Self { text: String::new(), style: self.style, link: self.link.clone(), is_frame: self.is_frame }
109    }
110}
111
112#[derive(Clone, Debug, Default, PartialEq, Eq)]
113pub struct Line {
114    pub spans: Vec<Span>,
115}
116
117impl Line {
118    pub fn new(spans: Vec<Span>) -> Self {
119        Self { spans }
120    }
121
122    /// A line of text slices, each styled and linked as its span, neighbours that look alike joined into one span.
123    /// Every span and text is allocated at its exact size: documents hold millions of lines, and growth by doubling
124    /// would leave up to half of each spare.
125    pub(crate) fn joined<'a>(pieces: impl IntoIterator<Item = (&'a str, &'a Span)>) -> Self {
126        let pieces: Vec<(&str, &Span)> = pieces.into_iter().collect();
127        let runs = pieces.chunk_by(|(_, left), (_, right)| left.looks_like(right));
128        let mut spans = Vec::with_capacity(runs.clone().count());
129        spans.extend(runs.map(|run| {
130            let mut text = String::with_capacity(run.iter().map(|(piece, _)| piece.len()).sum());
131            text.extend(run.iter().map(|(piece, _)| *piece));
132            let (_, first) = run[0];
133            Span { text, ..first.without_text() }
134        }));
135        Self::new(spans)
136    }
137
138    pub fn blank() -> Self {
139        Self::default()
140    }
141
142    pub fn width(&self) -> usize {
143        crate::text::spans_width(&self.spans)
144    }
145
146    /// The text as the input wrote it, escape sequences included: for searching and comparing, never for printing.
147    pub fn plain(&self) -> String {
148        crate::text::joined(&self.spans)
149    }
150
151    /// The text safe to write to a terminal: `plain` through [`sanitize::text`].
152    pub fn printable(&self) -> String {
153        sanitize::text(&self.plain())
154    }
155}
156
157/// A PNG and the terminal cell box it is drawn into.
158#[derive(Clone, Debug, PartialEq, Eq)]
159#[non_exhaustive]
160pub struct Picture {
161    pub png: Vec<u8>,
162    pub cols: u16,
163    pub rows: u16,
164    pub alt: String,
165    /// The bars and spaces of the lists and quotes around the picture, drawn left of each of its rows; the picture
166    /// starts right after it.
167    pub indent: Line,
168    /// Text written concealed in the picture's first row, under the picture, so selecting the picture copies it.
169    pub concealed_text: Option<String>,
170}
171
172#[derive(Clone, Debug, PartialEq, Eq)]
173#[non_exhaustive]
174pub enum Block {
175    Lines(Vec<Line>),
176    Picture(Picture),
177    /// Lines twice as tall and wide, each written on two rows as its top and bottom half.
178    DoubleHeight(Vec<Line>),
179}
180
181impl Block {
182    /// The text lines of the block, none for a picture.
183    pub fn lines(&self) -> &[Line] {
184        match self {
185            Block::Lines(lines) | Block::DoubleHeight(lines) => lines,
186            Block::Picture(_) => &[],
187        }
188    }
189}
190
191#[derive(Clone, Debug, Default, PartialEq, Eq)]
192pub struct Document {
193    pub blocks: Vec<Block>,
194}
195
196/// Size of one terminal cell in pixels; present only when pictures can be drawn.
197#[derive(Clone, Copy, Debug, PartialEq, Eq)]
198pub struct CellSize {
199    pub width_px: u16,
200    pub height_px: u16,
201}
202
203/// How a level-1 heading is drawn two rows tall, when asked for and the terminal can.
204#[derive(Clone, Copy, Debug, PartialEq, Eq)]
205#[non_exhaustive]
206pub enum JumboTitle {
207    /// A picture of each line over its concealed text.
208    Picture,
209    /// Double-height text (DECDHL).
210    DoubleHeight,
211}
212
213/// The narrowest width the renderers lay out at: a code panel needs its padding, its continuation marker and a wide
214/// grapheme side by side. A narrower `Settings::width` is laid out this wide.
215pub const MIN_WIDTH: usize = 8;
216
217#[derive(Clone, Debug, PartialEq)]
218#[non_exhaustive]
219pub struct Settings {
220    pub width: usize,
221    pub theme: Theme,
222    pub cell: Option<CellSize>,
223    /// Whether the terminal makes links clickable; when it does not, a link's target is printed after its text.
224    pub hyperlinks: bool,
225    pub jumbo_title: Option<JumboTitle>,
226    /// What a relative link target (`docs/x.md`, `/uploads/a.pdf`) resolves against, so it can be clicked; `None`
227    /// leaves it unclickable, its target printed after its text.
228    pub link_base: Option<LinkBase>,
229    /// When diagrams stop being laid out: each runs on a thread of its own, given up on at that moment, and those
230    /// left show as source. `None` lays every diagram out on the calling thread, bounded by the diagram budget alone.
231    pub diagram_deadline: Option<Instant>,
232}
233
234/// 80 columns of `mrk-dark` text: no pictures, links not clickable (their target printed after them), no jumbo title, no
235/// link base, no diagram deadline.
236impl Default for Settings {
237    fn default() -> Self {
238        Self {
239            width: 80,
240            theme: crate::theme::MRK_DARK,
241            cell: None,
242            hyperlinks: false,
243            jumbo_title: None,
244            link_base: None,
245            diagram_deadline: None,
246        }
247    }
248}
249
250/// The settings unit tests render with: the defaults, links clickable.
251#[cfg(test)]
252pub(crate) fn test_settings() -> Settings {
253    Settings { hyperlinks: true, ..Settings::default() }
254}
255
256/// The document as bare text, one `[picture: alt cols×rows]` line per picture and each double-height line twice:
257/// what snapshot tests compare. It keeps the input's escape sequences, so never print it; print `printable` instead.
258pub fn plain(document: &Document) -> String {
259    document.blocks.iter().map(plain_block).collect()
260}
261
262/// `plain` safe to write to a terminal: through [`sanitize::lines`].
263pub fn printable(document: &Document) -> String {
264    sanitize::lines(&plain(document))
265}
266
267fn plain_block(block: &Block) -> String {
268    match block {
269        Block::Lines(lines) => lines.iter().map(|line| format!("{}\n", line.plain().trim_end())).collect(),
270        Block::Picture(picture) => format!("{}[picture: {} {}×{}]\n", picture.indent.plain(), picture.alt, picture.cols, picture.rows),
271        Block::DoubleHeight(lines) => lines.iter().map(|line| format!("{0}\n{0}\n", line.plain().trim_end())).collect(),
272    }
273}
274
275/// `span` cut where a range starts or ends inside it, the pieces inside restyled; `first` is the offset of its first
276/// char, `ranges` are `normalized`. A span no range touches comes back whole.
277fn split_span(span: &Span, first: usize, ranges: &[Range<usize>], restyle: &impl Fn(Style) -> Style) -> Vec<Span> {
278    let end = first + span.text.chars().count();
279    let touching = ranges[ranges.partition_point(|range| range.end <= first)..].iter().take_while(|range| range.start < end);
280    let piece = |text: &str, style: Style| Span { text: text.to_owned(), style, ..span.without_text() };
281    let mut pieces = Vec::new();
282    let (mut at, mut rest) = (first, span.text.as_str());
283    for range in touching.map(|range| range.start.max(first)..range.end.min(end)) {
284        let (outside, tail) = split_chars(rest, range.start - at);
285        let (inside, tail) = split_chars(tail, range.len());
286        pieces.extend((!outside.is_empty()).then(|| piece(outside, span.style)));
287        pieces.push(piece(inside, restyle(span.style)));
288        (at, rest) = (range.end, tail);
289    }
290    if pieces.is_empty() || !rest.is_empty() {
291        pieces.push(piece(rest, span.style));
292    }
293    pieces
294}
295
296fn split_chars(text: &str, count: usize) -> (&str, &str) {
297    text.split_at(text.char_indices().nth(count).map_or(text.len(), |(index, _)| index))
298}
299
300/// The ranges sorted, the ones that overlap or touch merged and the empty ones dropped, so cuts never repeat.
301fn normalized(ranges: &[Range<usize>]) -> Vec<Range<usize>> {
302    let mut sorted: Vec<Range<usize>> = ranges.iter().filter(|range| !range.is_empty()).cloned().collect();
303    sorted.sort_unstable_by_key(|range| range.start);
304    sorted.into_iter().fold(Vec::new(), |mut merged: Vec<Range<usize>>, range| {
305        match merged.last_mut() {
306            Some(last) if range.start <= last.end => last.end = last.end.max(range.end),
307            _ => merged.push(range),
308        }
309        merged
310    })
311}
312
313/// The char offset in `plain` text at which each span starts, spans and lines taken in order with nothing between them.
314fn span_offsets(lines: &[Line]) -> impl Iterator<Item = usize> {
315    lines.iter().flat_map(|line| &line.spans).scan(0, |next, span| {
316        let first = *next;
317        *next += span.text.chars().count();
318        Some(first)
319    })
320}
321
322/// Restyles the text inside `ranges`, for a search match or a word-level diff; text, widths and links never change.
323///
324/// Ranges are char offsets into the lines' plain text joined with no separator,
325/// `lines.iter().map(Line::plain).collect::<String>()`, in any order; overlapping ones restyle once. A span is split
326/// where a range starts or ends inside it.
327pub fn highlight(lines: &[Line], ranges: &[Range<usize>], restyle: impl Fn(Style) -> Style) -> Vec<Line> {
328    let ranges = normalized(ranges);
329    let mut offsets = span_offsets(lines);
330    lines
331        .iter()
332        .map(|line| {
333            let spans = line.spans.iter().zip(offsets.by_ref()).flat_map(|(span, first)| split_span(span, first, &ranges, &restyle));
334            Line::new(spans.collect())
335        })
336        .collect()
337}
338
339#[cfg(test)]
340mod tests {
341    #![allow(clippy::single_range_in_vec_init)]
342
343    use super::*;
344
345    const RED: Rgb = Rgb(255, 0, 0);
346
347    #[test]
348    fn printable_text_carries_no_escape_sequence_while_plain_keeps_the_input() {
349        let line = Line::new(vec![Span::plain("hi \x1b]52;c;AAAA\x07"), Span::plain(" there")]);
350
351        assert_eq!(line.plain(), "hi \x1b]52;c;AAAA\x07 there");
352        assert_eq!(line.printable(), "hi ]52;c;AAAA there");
353    }
354
355    #[test]
356    fn a_printable_document_keeps_its_line_breaks_and_loses_escape_sequences() {
357        let line = Line::new(vec![Span::plain("a\x1b[2J")]);
358        let document = Document { blocks: vec![Block::Lines(vec![line.clone(), line])] };
359
360        assert_eq!(printable(&document), "a[2J\na[2J\n");
361    }
362
363    #[test]
364    fn mix_moves_each_channel_toward_the_other_colour_and_rounds() {
365        let black = Rgb(0, 0, 0);
366
367        assert_eq!(black.mix(RED, 0.0), black);
368        assert_eq!(black.mix(RED, 1.0), RED);
369        assert_eq!(Rgb(10, 200, 0).mix(Rgb(20, 100, 255), 0.25), Rgb(13, 175, 64));
370    }
371
372    #[test]
373    fn plain_joins_spans_and_trims_trailing_padding() {
374        let line = Line::new(vec![Span::plain("a "), Span::plain("b   ")]);
375        let document = Document { blocks: vec![Block::Lines(vec![line, Line::blank()])] };
376
377        assert_eq!(plain(&document), "a b\n\n");
378    }
379
380    #[test]
381    fn plain_draws_a_picture_after_its_indent() {
382        let picture = Picture {
383            png: Vec::new(),
384            cols: 4,
385            rows: 2,
386            alt: "flow".to_owned(),
387            indent: Line::new(vec![Span::plain("│ ")]),
388            concealed_text: None,
389        };
390
391        assert_eq!(plain(&Document { blocks: vec![Block::Picture(picture)] }), "│ [picture: flow 4×2]\n");
392    }
393
394    #[test]
395    fn plain_writes_a_double_height_line_on_its_two_rows() {
396        let document = Document { blocks: vec![Block::DoubleHeight(vec![Line::new(vec![Span::plain("Big ")])])] };
397
398        assert_eq!(plain(&document), "Big\nBig\n");
399    }
400
401    #[test]
402    fn hex_writes_two_digits_per_channel() {
403        assert_eq!(Rgb(0, 15, 255).hex(), "#000fff");
404    }
405
406    #[test]
407    fn joined_merges_neighbours_of_the_same_look_into_spans_of_exact_size() {
408        let (plain, red) = (Span::plain("a"), Span::new("b", Style::fg(RED)));
409
410        let line = Line::joined([("ab", &plain), ("c", &plain), ("d", &red), ("e", &plain)]);
411
412        assert_eq!(line.spans, [Span::plain("abc"), Span::new("d", Style::fg(RED)), Span::plain("e")]);
413        assert_eq!((line.spans.capacity(), line.spans[0].text.capacity()), (3, 3));
414    }
415
416    #[test]
417    fn joined_keeps_neighbours_with_different_links_apart() {
418        let (plain, linked) = (Span::plain("a"), Span::plain("b").linked("https://x.y"));
419
420        let line = Line::joined([("a", &plain), ("b", &linked), ("c", &linked)]);
421
422        assert_eq!(line.spans, [Span::plain("a"), Span::plain("bc").linked("https://x.y")]);
423        assert_eq!(Line::joined([("a", &plain), ("b", &plain.clone().framed())]).spans.len(), 2);
424    }
425
426    #[test]
427    fn line_width_counts_cells_not_bytes() {
428        let line = Line::new(vec![Span::plain("é漢")]);
429
430        assert_eq!(line.width(), 3);
431    }
432
433    #[test]
434    fn highlight_splits_spans_at_the_range_edges_and_keeps_links() {
435        let line =
436            Line::new(vec![Span::new("say hel", Style::fg(RED)), Span::new("lo world", Style::fg(RED).bold()).linked("https://x.y")]);
437
438        let lit = highlight(&[line], &[4..9], Style::underline);
439
440        assert_eq!(
441            lit[0].spans,
442            [
443                Span::new("say ", Style::fg(RED)),
444                Span::new("hel", Style::fg(RED).underline()),
445                Span::new("lo", Style::fg(RED).bold().underline()).linked("https://x.y"),
446                Span::new(" world", Style::fg(RED).bold()).linked("https://x.y"),
447            ]
448        );
449    }
450
451    #[test]
452    fn highlight_crosses_a_line_break_without_changing_the_text() {
453        let lines = [Line::new(vec![Span::plain("one two")]), Line::new(vec![Span::plain("three")])];
454
455        let lit = highlight(&lines, &[4..9], Style::bold);
456
457        assert_eq!(lit[0].spans, [Span::plain("one "), Span::new("two", Style::default().bold())]);
458        assert_eq!(lit[1].spans, [Span::new("th", Style::default().bold()), Span::plain("ree")]);
459        assert_eq!(lit.iter().map(Line::width).collect::<Vec<_>>(), [7, 5]);
460    }
461
462    #[test]
463    fn neighbouring_ranges_restyle_as_one_piece_and_a_range_over_a_whole_span_keeps_it_whole() {
464        let line = Line::new(vec![Span::plain("abcd"), Span::plain("ef")]);
465
466        let lit = highlight(&[line], &[1..2, 2..3, 4..6], Style::bold);
467
468        assert_eq!(
469            lit[0].spans,
470            [Span::plain("a"), Span::new("bc", Style::default().bold()), Span::plain("d"), Span::new("ef", Style::default().bold())]
471        );
472    }
473
474    #[test]
475    fn ranges_in_any_order_overlapping_or_repeated_cut_each_edge_once() {
476        let lines = [Line::new(vec![Span::plain("abcdef")])];
477        let bold = Style::default().bold();
478
479        let lit = highlight(&lines, &[4..5, 1..3, 2..3, 1..3, 5..5], Style::bold);
480
481        assert_eq!(lit[0].spans, [Span::plain("a"), Span::new("bc", bold), Span::plain("d"), Span::new("e", bold), Span::plain("f")]);
482    }
483
484    #[test]
485    fn an_empty_range_changes_nothing() {
486        let lines = [Line::new(vec![Span::plain("abc")])];
487
488        assert_eq!(highlight(&lines, &[1..1], Style::bold), lines);
489    }
490}