styled_str/style_diff/
mod.rs

1//! Comparing `Styled` instances by styling.
2
3use alloc::{format, string::String, vec::Vec};
4use core::{
5    cmp::{self, Ordering},
6    fmt,
7    iter::{self, Peekable},
8    mem,
9    num::NonZeroUsize,
10};
11
12use anstyle::{AnsiColor, Color, Effects, Style};
13use unicode_width::UnicodeWidthStr;
14
15use crate::{StyledStr, rich_parser::RichStyle, types::StyledSpan};
16
17#[cfg(test)]
18mod tests;
19
20impl StyledSpan {
21    /// Writes a single plaintext `line` to `out` using styles from `spans_iter`.
22    fn write_line<I>(
23        formatter: &mut fmt::Formatter<'_>,
24        spans_iter: &mut Peekable<I>,
25        line_start: usize,
26        line: &str,
27    ) -> fmt::Result
28    where
29        I: Iterator<Item = Self>,
30    {
31        let mut pos = 0;
32        while pos < line.len() {
33            let span = spans_iter.peek().expect("spans ended before lines");
34            let span_len = span.len.get() - line_start.saturating_sub(span.start);
35
36            let span_end = cmp::min(pos + span_len, line.len());
37            write!(
38                formatter,
39                "{style}{}{style:#}",
40                &line[pos..span_end],
41                style = span.style
42            )?;
43            if span_end == pos + span_len {
44                // The span has ended, can proceed to the next one.
45                spans_iter.next();
46            }
47            pos += span_len;
48        }
49        writeln!(formatter)
50    }
51}
52
53#[derive(Debug)]
54struct DiffStyleSpan {
55    start: usize,
56    len: NonZeroUsize,
57    lhs_style: Style,
58    rhs_style: Style,
59}
60
61impl DiffStyleSpan {
62    /// Would this style be visible on whitespace (e.g., ' ' or '\t')?
63    fn affects_whitespace(style: &Style) -> bool {
64        let effects = style.get_effects();
65        if effects.contains(Effects::UNDERLINE)
66            || effects.contains(Effects::STRIKETHROUGH)
67            || effects.contains(Effects::INVERT)
68        {
69            return true;
70        }
71        // We've handled the case with inverted colors above, so we check the background color specifically
72        style.get_bg_color().is_some()
73    }
74
75    /// Trims whitespace at the start and end of the string; we don't care about diffs there.
76    fn new(diff_text: &str, start: usize, lhs_style: Style, rhs_style: Style) -> Option<Self> {
77        debug_assert_ne!(diff_text, "");
78
79        let affects_whitespace =
80            Self::affects_whitespace(&lhs_style) || Self::affects_whitespace(&rhs_style);
81        let can_trim = |ch: char| {
82            if affects_whitespace {
83                // Newline chars are not affected by any styles
84                ch == '\n' || ch == '\r'
85            } else {
86                ch.is_whitespace()
87            }
88        };
89
90        let first_pos = diff_text
91            .char_indices()
92            .find_map(|(i, ch)| (!can_trim(ch)).then_some(i))?;
93        let last_pos = diff_text
94            .char_indices()
95            .rev()
96            .find_map(|(i, ch)| (!can_trim(ch)).then_some(i + ch.len_utf8()))?;
97        debug_assert!(last_pos > first_pos);
98
99        Some(Self {
100            start: start + first_pos,
101            len: NonZeroUsize::new(last_pos - first_pos)?,
102            lhs_style,
103            rhs_style,
104        })
105    }
106}
107
108const STYLE_WIDTH: usize = 25;
109
110/// Difference in styles between two [styled strings](StyledStr) that can be output in detailed
111/// human-readable format via [`Display`](fmt::Display).
112///
113/// The `Display` implementation supports two output formats:
114///
115/// - With the default / non-alternate format (e.g., `{}`), the diff will be output as the LHS line-by-line,
116///   highlighting differences in styles on each differing line.
117/// - With the alternate format (`{:#}`), the diff will be output as a table of all differing spans.
118///
119/// # Examples
120///
121/// ```
122/// use styled_str::{styled, StyleDiff, StyledString};
123///
124/// let lhs = styled!("[[red on white]]Hello,[[/]] [[bold green]]world!");
125/// let rhs = styled!("[[red on white!]]Hello,[[/]] [[bold green]]world[[/]]!");
126/// let diff = StyleDiff::new(lhs, rhs);
127/// assert!(!diff.is_empty());
128///
129/// let diff_str = StyledString::from_ansi(&format!("{diff}"))?;
130/// assert_eq!(
131///     diff_str.text(),
132///     "> Hello, world!\n\
133///      > ^^^^^^      ^\n"
134/// );
135///
136/// let diff_str = StyledString::from_ansi(&format!("{diff:#}"))?;
137/// let expected =
138///     "|Positions         Left style                Right style       |
139///      |========== ========================= =========================|
140///      |      0..6       red on white              red on white!      |
141///      |    12..13        bold green                  (none)          |";
142/// let expected: String = expected
143///     .lines()
144///     .flat_map(|line| [line.trim().trim_matches('|'), "\n"])
145///     .collect();
146/// assert_eq!(diff_str.text(), expected);
147/// # anyhow::Ok(())
148/// ```
149#[derive(Debug)]
150pub struct StyleDiff<'a> {
151    lhs: StyledStr<'a>,
152    differing_spans: Vec<DiffStyleSpan>,
153}
154
155impl fmt::Display for StyleDiff<'_> {
156    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
157        if formatter.alternate() {
158            self.write_as_table(formatter)
159        } else {
160            self.highlight_text(formatter)
161        }
162    }
163}
164
165impl<'a> StyleDiff<'a> {
166    /// Computes style difference between two styled strings.
167    ///
168    /// # Panics
169    ///
170    /// Panics if `lhs` and `rhs` have differing lengths.
171    pub fn new(lhs: StyledStr<'a>, rhs: StyledStr<'a>) -> Self {
172        assert_eq!(
173            lhs.text.len(),
174            rhs.text.len(),
175            "Compared strings must have same length"
176        );
177
178        let mut this = Self {
179            lhs,
180            differing_spans: Vec::new(),
181        };
182        let mut pos = 0;
183        let mut lhs_iter = lhs.spans.iter();
184        let Some(mut lhs_span) = lhs_iter.next() else {
185            return this;
186        };
187        let mut rhs_iter = rhs.spans.iter();
188        let Some(mut rhs_span) = rhs_iter.next() else {
189            return this;
190        };
191
192        loop {
193            let common_len = cmp::min(lhs_span.len, rhs_span.len);
194
195            // Record a diff span if the color specs differ.
196            if lhs_span.style != rhs_span.style {
197                let diff_text = &this.lhs.text[pos..pos + common_len.get()];
198                this.differing_spans.extend(DiffStyleSpan::new(
199                    diff_text,
200                    pos,
201                    lhs_span.style,
202                    rhs_span.style,
203                ));
204            }
205
206            pos += common_len.get();
207
208            match lhs_span.len.cmp(&rhs_span.len) {
209                Ordering::Less => {
210                    rhs_span.shrink_len(lhs_span.len.get());
211                    lhs_span = lhs_iter.next().unwrap();
212                    // ^ `unwrap()` here and below are safe; we've checked that
213                    // `lhs` and `rhs` contain same total span coverage.
214                }
215                Ordering::Greater => {
216                    lhs_span.shrink_len(rhs_span.len.get());
217                    rhs_span = rhs_iter.next().unwrap();
218                }
219                Ordering::Equal => {
220                    lhs_span = match lhs_iter.next() {
221                        Some(span) => span,
222                        None => return this,
223                    };
224                    rhs_span = match rhs_iter.next() {
225                        Some(span) => span,
226                        None => return this,
227                    };
228                }
229            }
230        }
231    }
232
233    /// Checks whether this difference is empty.
234    pub fn is_empty(&self) -> bool {
235        self.differing_spans.is_empty()
236    }
237
238    /// Highlights this diff on the specified `text` which has styling set with `color_spans`.
239    fn highlight_text(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
240        const SIDELINE_HL: Style = Style::new().fg_color(Some(Color::Ansi(AnsiColor::Red)));
241
242        let highlights = HighlightedSpan::new(&self.differing_spans);
243        let mut highlights = highlights.iter().copied().peekable();
244        let mut line_start = 0;
245
246        let mut color_spans = self.lhs.spans.iter().peekable();
247
248        for line in self.lhs.text.split('\n') {
249            let line_contains_spans = highlights
250                .peek()
251                .is_some_and(|span| span.start <= line_start + line.len());
252
253            if line_contains_spans {
254                write!(formatter, "{SIDELINE_HL}> {SIDELINE_HL:#}")?;
255                StyledSpan::write_line(formatter, &mut color_spans, line_start, line)?;
256                write!(formatter, "{SIDELINE_HL}> {SIDELINE_HL:#}")?;
257                Self::highlight_line(formatter, &mut highlights, line_start, line)?;
258            } else {
259                write!(formatter, "= ")?;
260                StyledSpan::write_line(formatter, &mut color_spans, line_start, line)?;
261            }
262            line_start += line.len() + 1;
263        }
264        Ok(())
265    }
266
267    fn highlight_line<I>(
268        out: &mut fmt::Formatter<'_>,
269        spans_iter: &mut Peekable<I>,
270        line_offset: usize,
271        line: &str,
272    ) -> fmt::Result
273    where
274        I: Iterator<Item = HighlightedSpan>,
275    {
276        let line_len = line.len();
277        let mut line_pos = 0;
278
279        while line_pos < line_len {
280            let Some(span) = spans_iter.peek() else {
281                break;
282            };
283            let span_start = span.start.saturating_sub(line_offset);
284            if span_start >= line_len {
285                break;
286            }
287            let span_end = cmp::min(span.start + span.len.get() - line_offset, line_len);
288
289            if span_start > line_pos {
290                let spaces = " ".repeat(line[line_pos..span_start].width());
291                write!(out, "{spaces}")?;
292            }
293
294            let ch = span.kind.underline_char();
295            let underline: String =
296                iter::repeat_n(ch, line[span_start..span_end].width()).collect();
297            let hl = span.kind.highlight_style();
298            write!(out, "{hl}{underline}{hl:#}")?;
299
300            line_pos = span_end;
301            if span.start + span.len.get() <= line_offset + line_len {
302                // Span is finished on this line; can proceed to the next one.
303                spans_iter.next();
304            }
305        }
306        writeln!(out)
307    }
308
309    pub(crate) fn write_as_table(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
310        const TABLE_HEAD: Style = Style::new().bold();
311        const POS_WIDTH: usize = 10;
312
313        // Write table header.
314        writeln!(
315            formatter,
316            "{TABLE_HEAD}{pos:^POS_WIDTH$} {lhs:^STYLE_WIDTH$} {rhs:^STYLE_WIDTH$}",
317            pos = "Positions",
318            lhs = "Left style",
319            rhs = "Right style"
320        )?;
321        writeln!(
322            formatter,
323            "{pos:=>POS_WIDTH$} {lhs:=>STYLE_WIDTH$} {rhs:=>STYLE_WIDTH$}{TABLE_HEAD:#}",
324            pos = "",
325            lhs = "",
326            rhs = ""
327        )?;
328
329        // Write table itself.
330        for differing_span in &self.differing_spans {
331            let lhs_style = &differing_span.lhs_style;
332            let mut lhs_lines = Self::write_style(lhs_style);
333            let rhs_style = &differing_span.rhs_style;
334            let mut rhs_lines = Self::write_style(rhs_style);
335            if lhs_lines.len() < rhs_lines.len() {
336                lhs_lines.resize_with(rhs_lines.len(), String::new);
337            } else {
338                rhs_lines.resize_with(lhs_lines.len(), String::new);
339            }
340
341            for (i, (lhs_line, rhs_line)) in lhs_lines.into_iter().zip(rhs_lines).enumerate() {
342                if i == 0 {
343                    let start = differing_span.start;
344                    let end = start + differing_span.len.get();
345                    let pos = format!("{start}..{end}");
346                    write!(formatter, "{pos:>POS_WIDTH$} ")?;
347                } else {
348                    write!(formatter, "{:>POS_WIDTH$} ", "")?;
349                }
350                writeln!(
351                    formatter,
352                    "{lhs_style}{lhs_line:^STYLE_WIDTH$}{lhs_style:#} \
353                     {rhs_style}{rhs_line:^STYLE_WIDTH$}{rhs_style:#}"
354                )?;
355            }
356        }
357
358        Ok(())
359    }
360
361    /// Writes `color_spec` in human-readable format.
362    fn write_style(style: &Style) -> Vec<String> {
363        let mut tokens = RichStyle(style).tokens();
364        if tokens.is_empty() {
365            tokens.push("(none)".into());
366        }
367
368        let mut lines = Vec::new();
369        let mut current_line = String::new();
370        for token in tokens {
371            // We can use `len()` because all text is ASCII.
372            if !current_line.is_empty() && current_line.len() + 1 + token.len() > STYLE_WIDTH {
373                lines.push(mem::take(&mut current_line));
374            }
375            if !current_line.is_empty() {
376                current_line.push(' ');
377            }
378            current_line.push_str(&token);
379        }
380
381        if !current_line.is_empty() {
382            lines.push(current_line);
383        }
384        lines
385    }
386}
387
388#[derive(Debug, Clone, Copy)]
389enum SpanHighlightKind {
390    Main,
391    Aux,
392}
393
394impl SpanHighlightKind {
395    fn underline_char(self) -> char {
396        match self {
397            Self::Main => '^',
398            Self::Aux => '!',
399        }
400    }
401
402    fn highlight_style(self) -> Style {
403        let mut style = Style::new();
404        match self {
405            Self::Main => {
406                style = style
407                    .fg_color(Some(AnsiColor::White.into()))
408                    .bg_color(Some(AnsiColor::Red.into()));
409            }
410            Self::Aux => {
411                style = style
412                    .fg_color(Some(AnsiColor::Black.into()))
413                    .bg_color(Some(AnsiColor::Yellow.into()));
414            }
415        }
416        style
417    }
418}
419
420#[derive(Debug, Clone, Copy)]
421struct HighlightedSpan {
422    start: usize,
423    len: NonZeroUsize,
424    kind: SpanHighlightKind,
425}
426
427impl HighlightedSpan {
428    fn new(differing_spans: &[DiffStyleSpan]) -> Vec<Self> {
429        let mut sequential_span_count = 1;
430        let span_highlights = differing_spans.windows(2).map(|window| match window {
431            [prev, next] => {
432                if prev.start + prev.len.get() == next.start {
433                    sequential_span_count += 1;
434                } else {
435                    sequential_span_count = 1;
436                }
437                if sequential_span_count % 2 == 0 {
438                    SpanHighlightKind::Aux
439                } else {
440                    SpanHighlightKind::Main
441                }
442            }
443            _ => unreachable!(),
444        });
445
446        iter::once(SpanHighlightKind::Main)
447            .chain(span_highlights)
448            .zip(differing_spans)
449            .map(|(kind, span)| Self {
450                start: span.start,
451                len: span.len,
452                kind,
453            })
454            .collect()
455    }
456}