Skip to main content

jubarte_edit/
text_diff.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2// SPDX-License-Identifier: Apache-2.0
3
4//! Git/GitHub unified patches of complete document text snapshots, and
5//! other review presentations.
6//!
7//! DOCX snapshots use the same paragraph, table, and revision-mark view
8//! as `jubarte debug --check text`, without clipping or a hunk limit.
9//! The patches are for review only; they do not patch the binary DOCX
10//! package. They back `jubarte diff` and the Python and WASM bindings'
11//! `diff_text` / `diff_documents` shapes.
12
13use crate::markdown::Source;
14use similar::{ChangeTag, DiffOp, DiffTag, TextDiff};
15use std::fmt::Write as _;
16use std::ops::Range;
17
18/// Names written on the patch headers and the number of unchanged
19/// context lines around each change. Git's `a/` and `b/` prefixes are
20/// added automatically by every formatter that prints them.
21#[derive(Clone, Debug)]
22pub struct UnifiedOptions {
23    /// Original document label (Git's `a/` prefix is added automatically).
24    pub old_name: String,
25    /// Modified document label (Git's `b/` prefix is added automatically).
26    pub new_name: String,
27    /// Number of unchanged lines around each change; defaults to three.
28    pub context: usize,
29}
30
31impl Default for UnifiedOptions {
32    fn default() -> Self {
33        Self {
34            old_name: "old.docx".into(),
35            new_name: "new.docx".into(),
36            context: 3,
37        }
38    }
39}
40
41/// Presentation of a document's line changes.
42#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
43pub enum TextFormat {
44    /// Git headers and unified hunks, with the snapshots' tracked marks
45    /// carried into the changed lines as their existing CriticMarkup.
46    #[default]
47    Github,
48    /// Accept both inputs first, then emit fresh word-level CriticMarkup
49    /// on each changed line only.
50    Word,
51    /// Traditional `a`, `d`, `c` line addresses, without context lines.
52    Normal,
53    /// Traditional two-sided context blocks (`***`, `---`).
54    Context,
55    /// Aligned replacement, insertion and deletion rows, without
56    /// addresses; the default for [`Self::SideBySide`] adapts to a
57    /// `--window` wide enough for the text.
58    SideBySide,
59}
60
61/// Review presentation options for [`diff_text_view`] and
62/// [`diff_documents_view`]; the raw unified patch APIs above
63/// ([`diff_text`], [`diff_documents`]) stay unclipped.
64#[derive(Clone, Debug)]
65pub struct TextOptions {
66    /// Snapshot labels and surrounding unchanged lines.
67    pub unified: UnifiedOptions,
68    /// Output presentation; defaults to GitHub unified hunks.
69    pub format: TextFormat,
70    /// Accept the inputs' tracked changes before comparison (always true
71    /// when `format == TextFormat::Word`).
72    pub accept_changes: bool,
73    /// Per-line Unicode scalar window; `None` keeps complete lines. The
74    /// window counts characters only, never delimiters, so every mark a
75    /// line opens it closes.
76    pub window: Option<usize>,
77}
78
79/// The default window, in Unicode scalars.
80const WINDOW: usize = 70;
81
82impl Default for TextOptions {
83    fn default() -> Self {
84        Self {
85            unified: UnifiedOptions::default(),
86            format: TextFormat::Github,
87            accept_changes: false,
88            window: Some(WINDOW),
89        }
90    }
91}
92
93/// Compares two plain-text snapshots (`old`, `new`) in the review
94/// presentation `options.format` names.
95///
96/// Existing CriticMarkup stays inside the changed lines unless acceptance
97/// is requested. Word mode always accepts both inputs and emits only the
98/// changed lines with newly-generated CriticMarkup. Clipping (the
99/// `window`) happens after comparison, so it cannot hide a hunk or
100/// change its line ranges.
101pub fn diff_text_view(old: &str, new: &str, options: &TextOptions) -> String {
102    let accept = options.accept_changes || options.format == TextFormat::Word;
103    let old = accepted_text(old, accept);
104    let new = accepted_text(new, accept);
105    render_view(&old, &new, options)
106}
107
108/// Compares two DOCX bytes or Markdown text snapshots in the review
109/// presentation `options.format` names. DOCX revision acceptance runs on
110/// the package before text extraction, so removed paragraphs and table
111/// rows cannot contribute phantom line numbers.
112///
113/// # Inputs
114///
115/// - `old`, `new` — either two `.docx` byte slices or two Markdown strings
116///   ([`crate::markdown::Source`]).
117/// - `options` — review presentation, acceptance policy and `window`.
118///
119/// # Errors
120///
121/// A message when [`Source::Docx`] is given for `old` or `new` and the
122/// package cannot be admitted (a budget, a duplicate or unsafe part name,
123/// an encrypted `.docx`, an unsupported XML encoding, or the bytes are
124/// not a `.docx`).
125pub fn diff_documents_view(
126    old: Source<'_>,
127    new: Source<'_>,
128    options: &TextOptions,
129) -> Result<String, String> {
130    let accept = options.accept_changes || options.format == TextFormat::Word;
131    let critic = options.format != TextFormat::Word;
132    let old = view_snapshot(old, accept, critic)?;
133    let new = view_snapshot(new, accept, critic)?;
134    Ok(render_view(&old, &new, options))
135}
136
137fn accepted_text(text: &str, accept: bool) -> std::borrow::Cow<'_, str> {
138    if accept {
139        crate::markdown::accepted_clauses(text).into()
140    } else {
141        text.into()
142    }
143}
144
145fn view_snapshot(source: Source<'_>, accept: bool, critic: bool) -> Result<String, String> {
146    match source {
147        Source::Markdown(text) => Ok(accepted_text(text, accept).into_owned()),
148        Source::Docx(bytes) => {
149            crate::debug::document_text_view(bytes, critic, accept, critic_literal)
150        }
151    }
152}
153
154fn render_view(old: &str, new: &str, options: &TextOptions) -> String {
155    // CRLF and LF end the same document line. A missing final newline is
156    // marked by the formats that have a marker for it (GitHub, normal and
157    // context); word and side-by-side compare the lines it ends.
158    let terminate = !matches!(
159        options.format,
160        TextFormat::Github | TextFormat::Normal | TextFormat::Context
161    );
162    let (old, new) = (line_endings(old, terminate), line_endings(new, terminate));
163    let (old, new) = (old.as_ref(), new.as_ref());
164    if old == new {
165        return String::new();
166    }
167    if options.format == TextFormat::Github && options.window.is_none() {
168        return diff_text(old, new, &options.unified);
169    }
170    let diff = TextDiff::from_lines(old, new);
171    let context = options
172        .unified
173        .context
174        .min(diff.old_len().max(diff.new_len()));
175    match options.format {
176        TextFormat::Github => github_view(&diff, options, context),
177        TextFormat::Normal => normal_view(&diff, options),
178        TextFormat::Context => context_view(&diff, options, context),
179        TextFormat::Word | TextFormat::SideBySide => rows_view(&diff, options, context),
180    }
181}
182
183/// `text` with LF line ends, and with a final newline when `terminate`.
184fn line_endings(text: &str, terminate: bool) -> std::borrow::Cow<'_, str> {
185    let mut text = std::borrow::Cow::Borrowed(text);
186    if text.contains("\r\n") {
187        text = text.replace("\r\n", "\n").into();
188    }
189    if terminate && !text.is_empty() && !text.ends_with('\n') {
190        text.to_mut().push('\n');
191    }
192    text
193}
194
195/// GNU diff's marker after a last line with no newline.
196fn mark_unterminated(out: &mut String, line: Option<&str>) {
197    if line.is_some_and(|line| !line.ends_with('\n')) {
198        out.push_str("\\ No newline at end of file\n");
199    }
200}
201
202fn line(text: &str) -> &str {
203    let text = text.strip_suffix('\n').unwrap_or(text);
204    text.strip_suffix('\r').unwrap_or(text)
205}
206
207/// Window offsets and widths count Unicode scalars, never UTF-8 bytes.
208fn clip(text: &str, changed_at: usize, window: Option<usize>) -> String {
209    let Some(width) = window else {
210        return text.to_string();
211    };
212    let len = text.chars().count();
213    if len <= width {
214        return text.to_string();
215    }
216    let start = changed_at.saturating_sub(width / 2).min(len);
217    let end = start.saturating_add(width).min(len);
218    // The window's bytes, so the string is sized once (#1830).
219    let byte_at = |i: usize| text.char_indices().nth(i).map_or(text.len(), |(b, _)| b);
220    let window = &text[byte_at(start)..byte_at(end)];
221    let ellipses = usize::from(start > 0) + usize::from(end < len);
222    let mut out = String::with_capacity(window.len() + ellipses * '…'.len_utf8());
223    if start > 0 {
224        out.push('…');
225    }
226    out.push_str(window);
227    if end < len {
228        out.push('…');
229    }
230    out
231}
232
233fn first_difference(old: &str, new: &str) -> usize {
234    old.chars()
235        .zip(new.chars())
236        .take_while(|(a, b)| a == b)
237        .count()
238}
239
240#[derive(Debug, PartialEq, Eq)]
241enum Row {
242    Pair(usize, usize),
243    Delete(usize),
244    Insert(usize),
245}
246
247/// Use the upstream word diff to align similar clauses within a replacement.
248/// A bounded search avoids quadratic work for large, wholly rewritten hunks.
249/// Equal-sized unrelated tails still pair by position, as standard diff does.
250fn replacement_rows(old: &[&str], new: &[&str]) -> Vec<Row> {
251    if old.len().saturating_mul(new.len()) > 400 {
252        return positional_rows(old.len(), new.len());
253    }
254    let old_words: Vec<_> = old.iter().map(|text| matching_words(text)).collect();
255    let new_words: Vec<_> = new.iter().map(|text| matching_words(text)).collect();
256    let mut rows = Vec::with_capacity(old_words.len() + new_words.len());
257    let mut next = 0;
258    for (i, a) in old_words.iter().enumerate() {
259        let mut best = None;
260        let mut score = 0.3;
261        for (j, b) in new_words.iter().enumerate().skip(next) {
262            let ratio = TextDiff::from_slices(a, b).ratio();
263            if ratio > score {
264                score = ratio;
265                best = Some(j);
266            }
267        }
268        // A later old clause may be a much stronger match for this new row.
269        if let Some(j) = best {
270            let stronger = old_words
271                .iter()
272                .skip(i + 1)
273                .any(|a| TextDiff::from_slices(a, &new_words[j]).ratio() > score);
274            if stronger {
275                rows.push(Row::Delete(i));
276                continue;
277            }
278        }
279        let best = best
280            .or_else(|| (old.len() - i == new.len() - next && next < new.len()).then_some(next));
281        if let Some(j) = best {
282            rows.extend((next..j).map(Row::Insert));
283            rows.push(Row::Pair(i, j));
284            next = j + 1;
285        } else {
286            rows.push(Row::Delete(i));
287        }
288    }
289    rows.extend((next..new.len()).map(Row::Insert));
290    rows
291}
292
293fn matching_words(text: &str) -> Vec<&str> {
294    crate::util::word_tokens(text)
295        .into_iter()
296        .filter(|t| t.chars().any(char::is_alphanumeric))
297        .collect()
298}
299
300fn positional_rows(old_len: usize, new_len: usize) -> Vec<Row> {
301    let paired = old_len.min(new_len);
302    (0..paired)
303        .map(|i| Row::Pair(i, i))
304        .chain((paired..old_len).map(Row::Delete))
305        .chain((paired..new_len).map(Row::Insert))
306        .collect()
307}
308
309fn op_lines<'a>(diff: &'a TextDiff<'_, '_, str>, op: &DiffOp) -> (Vec<&'a str>, Vec<&'a str>) {
310    let old = op
311        .old_range()
312        .map(|i| line(&diff.old_lookup()[i]))
313        .collect();
314    let new = op
315        .new_range()
316        .map(|i| line(&diff.new_lookup()[i]))
317        .collect();
318    (old, new)
319}
320
321fn op_windows(
322    diff: &TextDiff<'_, '_, str>,
323    op: &DiffOp,
324    window: Option<usize>,
325) -> (Vec<String>, Vec<String>) {
326    let (old, new) = op_lines(diff, op);
327    let mut old_starts = vec![0; old.len()];
328    let mut new_starts = vec![0; new.len()];
329    if op.tag() == DiffTag::Replace {
330        for row in replacement_rows(&old, &new) {
331            if let Row::Pair(i, j) = row {
332                let at = first_difference(old[i], new[j]);
333                old_starts[i] = at;
334                new_starts[j] = at;
335            }
336        }
337    }
338    let olds = old
339        .iter()
340        .zip(old_starts)
341        .map(|(text, at)| clip(text, at, window))
342        .collect();
343    let news = new
344        .iter()
345        .zip(new_starts)
346        .map(|(text, at)| clip(text, at, window))
347        .collect();
348    (olds, news)
349}
350
351fn github_view(diff: &TextDiff<'_, '_, str>, options: &TextOptions, context: usize) -> String {
352    let old_name = git_path("a", &options.unified.old_name);
353    let new_name = git_path("b", &options.unified.new_name);
354    let mut out = format!("diff --git {old_name} {new_name}\n--- {old_name}\n+++ {new_name}\n");
355    for ops in diff.grouped_ops(context) {
356        let _ = writeln!(out, "{}", similar::udiff::UnifiedHunkHeader::new(&ops));
357        for op in &ops {
358            let (old, new) = op_windows(diff, op, options.window);
359            for change in diff.iter_changes(op) {
360                let text = match change.tag() {
361                    ChangeTag::Equal | ChangeTag::Delete => {
362                        &old[change.old_index().unwrap() - op.old_range().start]
363                    }
364                    ChangeTag::Insert => &new[change.new_index().unwrap() - op.new_range().start],
365                };
366                let _ = writeln!(out, "{}{text}", change.tag());
367                if change.missing_newline() {
368                    out.push_str("\\ No newline at end of file\n");
369                }
370            }
371        }
372    }
373    out
374}
375
376/// Nonempty ranges use inclusive, one-based addresses; empty ones name the
377/// preceding line (including line zero for an insertion at the beginning).
378fn address(range: &Range<usize>) -> String {
379    match range.len() {
380        0 => range.start.to_string(),
381        1 => range.end.to_string(),
382        _ => format!("{},{}", range.start + 1, range.end),
383    }
384}
385
386fn normal_view(diff: &TextDiff<'_, '_, str>, options: &TextOptions) -> String {
387    let mut out = String::new();
388    for op in diff.ops().iter().filter(|op| op.tag() != DiffTag::Equal) {
389        let letter = match op.tag() {
390            DiffTag::Insert => 'a',
391            DiffTag::Delete => 'd',
392            _ => 'c',
393        };
394        let _ = writeln!(
395            out,
396            "{}{letter}{}",
397            address(&op.old_range()),
398            address(&op.new_range())
399        );
400        let (old, new) = op_windows(diff, op, options.window);
401        for (index, text) in op.old_range().zip(old) {
402            let _ = writeln!(out, "< {text}");
403            mark_unterminated(&mut out, diff.old_slice(index));
404        }
405        if op.tag() == DiffTag::Replace {
406            out.push_str("---\n");
407        }
408        for (index, text) in op.new_range().zip(new) {
409            let _ = writeln!(out, "> {text}");
410            mark_unterminated(&mut out, diff.new_slice(index));
411        }
412    }
413    out
414}
415
416fn context_view(diff: &TextDiff<'_, '_, str>, options: &TextOptions, context: usize) -> String {
417    // Reuse Git quoting for labels, dropping only the synthetic side prefix.
418    let label = |name: &str| git_path("", name).replacen('/', "", 1);
419    let mut out = format!(
420        "*** {}\n--- {}\n",
421        label(&options.unified.old_name),
422        label(&options.unified.new_name)
423    );
424    for ops in diff.grouped_ops(context) {
425        let Some(first) = ops.first() else { continue };
426        let last = ops.last().unwrap();
427        let olds = first.old_range().start..last.old_range().end;
428        let news = first.new_range().start..last.new_range().end;
429        out.push_str("***************\n");
430        let _ = writeln!(out, "*** {} ****", address(&olds));
431        let windows: Vec<_> = ops
432            .iter()
433            .map(|op| op_windows(diff, op, options.window))
434            .collect();
435        for (op, (old, _)) in ops.iter().zip(&windows) {
436            let prefix = match op.tag() {
437                DiffTag::Equal => "  ",
438                DiffTag::Replace => "! ",
439                _ => "- ",
440            };
441            for (index, text) in op.old_range().zip(old) {
442                let _ = writeln!(out, "{prefix}{text}");
443                mark_unterminated(&mut out, diff.old_slice(index));
444            }
445        }
446        let _ = writeln!(out, "--- {} ----", address(&news));
447        for (op, (_, new)) in ops.iter().zip(&windows) {
448            let prefix = match op.tag() {
449                DiffTag::Equal => "  ",
450                DiffTag::Replace => "! ",
451                _ => "+ ",
452            };
453            for (index, text) in op.new_range().zip(new) {
454                let _ = writeln!(out, "{prefix}{text}");
455                mark_unterminated(&mut out, diff.new_slice(index));
456            }
457        }
458    }
459    out
460}
461
462/// Escape literal text before surrounding it with generated revision marks.
463/// Backslashes must be doubled before the renderer escapes mark delimiters.
464pub(crate) fn critic_literal(text: &str) -> String {
465    let text = text.replace('\\', "\\\\");
466    crate::markdown::diff_markdown(&text, &text)
467}
468
469/// One stretch of a word-level change line.
470enum Piece {
471    Same(String),
472    Delete(String),
473    Insert(String),
474    Replace(String, String),
475}
476
477impl Piece {
478    /// The texts the line shows, in order: one, or the old and new text.
479    fn texts(&self) -> [&str; 2] {
480        match self {
481            Self::Same(t) | Self::Delete(t) | Self::Insert(t) => [t, ""],
482            Self::Replace(a, b) => [a, b],
483        }
484    }
485
486    fn len(&self) -> usize {
487        self.texts().iter().map(|t| t.chars().count()).sum()
488    }
489}
490
491fn word_pieces(old: &str, new: &str) -> Vec<Piece> {
492    let old_tokens = crate::util::word_tokens(old);
493    let new_tokens = crate::util::word_tokens(new);
494    let diff = TextDiff::from_slices(&old_tokens, &new_tokens);
495    diff.ops()
496        .iter()
497        .map(|op| {
498            let a = old_tokens[op.old_range()].concat();
499            let b = new_tokens[op.new_range()].concat();
500            match op.tag() {
501                DiffTag::Equal => Piece::Same(a),
502                DiffTag::Delete => Piece::Delete(a),
503                DiffTag::Insert => Piece::Insert(b),
504                DiffTag::Replace => Piece::Replace(a, b),
505            }
506        })
507        .collect()
508}
509
510#[cfg(test)]
511fn word_change(old: &str, new: &str) -> String {
512    critic_line(&word_pieces(old, new), None)
513}
514
515/// The pieces as CriticMarkup, keeping `window` scalars of text around the
516/// first change. The window counts text, never delimiters: a mark it
517/// reaches keeps its delimiters and loses only text, so every mark the
518/// line opens, it closes. Text left out becomes `…`.
519fn critic_line(pieces: &[Piece], window: Option<usize>) -> String {
520    let len: usize = pieces.iter().map(Piece::len).sum();
521    let shown = match window {
522        Some(width) if len > width => {
523            let at: usize = pieces
524                .iter()
525                .take_while(|p| matches!(p, Piece::Same(_)))
526                .map(Piece::len)
527                .sum();
528            let start = at.saturating_sub(width / 2).min(len);
529            start..start.saturating_add(width).min(len)
530        }
531        _ => 0..len,
532    };
533    // The visible part of the text at `offset`, as scalar offsets into it.
534    let visible = |offset: usize, n: usize| {
535        let from = shown.start.clamp(offset, offset + n) - offset;
536        let to = shown.end.clamp(offset, offset + n) - offset;
537        (from < to).then_some((from, to))
538    };
539    let slice = |text: &str, (from, to): (usize, usize)| {
540        critic_literal(&text.chars().skip(from).take(to - from).collect::<String>())
541    };
542    let mut out = String::new();
543    let mut offset = 0;
544    // Text up to here is written or stands behind a `…`.
545    let mut covered = 0;
546    for piece in pieces {
547        let end = offset + piece.len();
548        let (open, close) = match piece {
549            Piece::Same(text) => {
550                let n = text.chars().count();
551                if let Some(part) = visible(offset, n) {
552                    if offset + part.0 > covered {
553                        out.push('…');
554                    }
555                    out.push_str(&slice(text, part));
556                    covered = offset + part.1;
557                }
558                offset = end;
559                continue;
560            }
561            Piece::Delete(_) => ("{--", "--}"),
562            Piece::Insert(_) => ("{++", "++}"),
563            Piece::Replace(..) => ("{~~", "~~}"),
564        };
565        if shown.start >= end || offset >= shown.end {
566            offset = end;
567            continue;
568        }
569        if offset > covered {
570            out.push('…');
571        }
572        out.push_str(open);
573        let texts = piece.texts();
574        let parts = if matches!(piece, Piece::Replace(..)) {
575            2
576        } else {
577            1
578        };
579        for (i, text) in texts.iter().take(parts).enumerate() {
580            if i == 1 {
581                out.push_str("~>");
582            }
583            // The window starts at or before the first change, so it never
584            // cuts a mark's text at its start; and a mark's text is never
585            // empty.
586            let n = text.chars().count();
587            match visible(offset, n) {
588                Some(part) => {
589                    out.push_str(&slice(text, part));
590                    if part.1 < n {
591                        out.push('…');
592                    }
593                }
594                None => out.push('…'),
595            }
596            offset += n;
597        }
598        out.push_str(close);
599        covered = end;
600    }
601    if covered < len {
602        out.push('…');
603    }
604    out
605}
606
607fn rows_view(diff: &TextDiff<'_, '_, str>, options: &TextOptions, context: usize) -> String {
608    let word = options.format == TextFormat::Word;
609    let mut out = String::new();
610    // Side-by-side rows: the old cell, the gutter mark, the new cell.
611    let mut side: Vec<(String, char, String)> = Vec::new();
612    let cut = |text: &str, at: usize| clip(text, at, options.window);
613    for ops in diff.grouped_ops(if word { 0 } else { context }) {
614        for op in &ops {
615            let (old, new) = op_lines(diff, op);
616            if op.tag() == DiffTag::Equal {
617                if !word {
618                    for text in old {
619                        let text = cut(text, 0);
620                        side.push((text.clone(), ' ', text));
621                    }
622                }
623                continue;
624            }
625            for row in replacement_rows(&old, &new) {
626                let (a, b) = match row {
627                    Row::Pair(i, j) => (old[i], new[j]),
628                    Row::Delete(i) => (old[i], ""),
629                    Row::Insert(j) => ("", new[j]),
630                };
631                if word {
632                    // A blank line has no word to mark: an empty mark keeps
633                    // its direction.
634                    let line = match row {
635                        Row::Delete(_) if a.is_empty() => "{----}".to_string(),
636                        Row::Insert(_) if b.is_empty() => "{++++}".to_string(),
637                        _ => critic_line(&word_pieces(a, b), options.window),
638                    };
639                    let _ = writeln!(out, "{line}");
640                    continue;
641                }
642                side.push(match row {
643                    Row::Pair(..) => {
644                        let at = first_difference(a, b);
645                        (cut(a, at), '|', cut(b, at))
646                    }
647                    Row::Delete(..) => (cut(a, 0), '<', String::new()),
648                    Row::Insert(..) => (String::new(), '>', cut(b, 0)),
649                });
650            }
651        }
652    }
653    // Pad the old column to its widest cell, in scalars like the window, so
654    // every gutter mark and every new cell starts in the same column. Whole
655    // lines pad no wider than a default window and its two `…`: one long
656    // paragraph would otherwise pad every row to its length. A longer old
657    // cell pushes only its own row's mark right.
658    let width = side
659        .iter()
660        .map(|(a, ..)| a.chars().count())
661        .max()
662        .unwrap_or(0)
663        .min(options.window.map_or(WINDOW + 2, |_| usize::MAX));
664    for (a, mark, b) in side {
665        if b.is_empty() {
666            let _ = writeln!(out, "{}", format!("{a:<width$} {mark}").trim_end());
667        } else {
668            let _ = writeln!(out, "{a:<width$} {mark} {b}");
669        }
670    }
671    out
672}
673
674/// Reads a complete textual snapshot of `source` — the same view
675/// `jubarte debug --check text` prints, preserving the snapshots'
676/// tracked marks. Kept for callers that need the raw text of one
677/// document before comparing it; the review paths go through
678/// [`diff_text_view`] / [`diff_documents_view`].
679///
680/// # Errors
681///
682/// A message when `source` is [`Source::Docx`] and the package cannot
683/// be admitted.
684pub fn document_text(source: Source<'_>) -> Result<String, String> {
685    match source {
686        Source::Markdown(text) => Ok(text.to_string()),
687        Source::Docx(bytes) => crate::debug::document_text(bytes),
688    }
689}
690
691/// Compares two plain-text snapshots (`old`, `new`) as a standard unified
692/// patch (Git C-style quoted names, `@@` hunk headers, `context`-line
693/// surroundings, `\ No newline at end of file` markers when the last line
694/// has no newline). Backs `jubarte diff` and the bindings; CRLF line ends
695/// are normalized to LF. Returns an empty string when `old == new`.
696pub fn diff_text(old: &str, new: &str, options: &UnifiedOptions) -> String {
697    if old == new {
698        return String::new();
699    }
700    let old_name = git_path("a", &options.old_name);
701    let new_name = git_path("b", &options.new_name);
702    let diff = similar::TextDiff::from_lines(old, new);
703    let hunks = diff
704        .unified_diff()
705        .context_radius(
706            options
707                .context
708                .min(old.lines().count().max(new.lines().count())),
709        )
710        .header(&old_name, &new_name)
711        .to_string();
712    format!("diff --git {old_name} {new_name}\n{hunks}")
713}
714
715// Git C-style path quoting keeps control characters out of patch headers.
716fn git_path(side: &str, name: &str) -> String {
717    let path = format!("{side}/{name}");
718    if !path
719        .chars()
720        .any(|c| c.is_control() || matches!(c, '"' | '\\' | ' '))
721    {
722        return path;
723    }
724    let mut out = String::from("\"");
725    for byte in path.bytes() {
726        match byte {
727            b'"' => out.push_str("\\\""),
728            b'\\' => out.push_str("\\\\"),
729            b'\t' => out.push_str("\\t"),
730            b'\n' => out.push_str("\\n"),
731            b'\r' => out.push_str("\\r"),
732            0..=31 | 127..=255 => {
733                use std::fmt::Write as _;
734                let _ = write!(out, "\\{byte:03o}");
735            }
736            _ => out.push(char::from(byte)),
737        }
738    }
739    out.push('"');
740    out
741}
742
743/// Compares two DOCX byte slices or two Markdown strings as a standard
744/// unified patch without constructing a redline. Backs `jubarte diff
745/// old.docx new.docx` and the bindings.
746///
747/// # Errors
748///
749/// A message when `old` or `new` is [`Source::Docx`] and the package
750/// cannot be admitted.
751pub fn diff_documents(
752    old: Source<'_>,
753    new: Source<'_>,
754    options: &UnifiedOptions,
755) -> Result<String, String> {
756    Ok(diff_text(
757        &document_text(old)?,
758        &document_text(new)?,
759        options,
760    ))
761}
762
763#[cfg(test)]
764#[cfg_attr(all(coverage_nightly, test), coverage(off))]
765mod tests {
766    use super::*;
767    use crate::markdown::{DocxOptions, markdown_to_docx};
768
769    fn word(text: &str) -> Vec<u8> {
770        markdown_to_docx(text, &DocxOptions::default())
771            .unwrap()
772            .docx
773    }
774
775    fn word_view(old: &str, new: &str, window: Option<usize>) -> String {
776        let options = TextOptions {
777            format: TextFormat::Word,
778            window,
779            ..Default::default()
780        };
781        diff_text_view(old, new, &options)
782    }
783
784    /// Every mark a line opens, it closes, in CriticMarkup order.
785    fn marks_close(line: &str) -> bool {
786        let mut rest = line;
787        while let Some(at) = ["{++", "{--", "{~~"]
788            .iter()
789            .filter_map(|open| rest.find(open))
790            .min()
791        {
792            let close: &[&str] = match &rest[at..at + 3] {
793                "{++" => &["++}"],
794                "{--" => &["--}"],
795                _ => &["~>", "~~}"],
796            };
797            rest = &rest[at + 3..];
798            for delimiter in close {
799                let Some(end) = rest.find(delimiter) else {
800                    return false;
801                };
802                if ["{++", "{--", "{~~"]
803                    .iter()
804                    .any(|o| rest[..end].contains(o))
805                {
806                    return false;
807                }
808                rest = &rest[end + delimiter.len()..];
809            }
810        }
811        !["++}", "--}", "~~}", "~>"].iter().any(|c| rest.contains(c))
812    }
813
814    #[test]
815    fn a_blank_line_change_keeps_its_direction_in_the_word_view() {
816        for window in [Some(70), None] {
817            assert_eq!(word_view("a\nb\n", "a\n\nb\n", window), "{++++}\n");
818            assert_eq!(word_view("a\n\nb\n", "a\nb\n", window), "{----}\n");
819            // A blank line replacing text is still the text's deletion.
820            assert_eq!(word_view("a\nx\nb\n", "a\n\nb\n", window), "{--x--}\n");
821        }
822    }
823
824    #[test]
825    fn a_word_window_keeps_every_mark_closed() {
826        let tail = "and the tail of an inserted clause that runs well past the window";
827        let cases = [
828            (
829                "Pay within thirty days.".to_string(),
830                format!("Pay within thirty days {tail}."),
831            ),
832            (format!("Pay {tail} now."), "Pay now.".to_string()),
833            ("Keep old wording here".to_string(), format!("Keep {tail}")),
834            (
835                format!("A {tail} B one C"),
836                format!("A {tail} B two C three D four"),
837            ),
838            (
839                format!("{} lead then old", "\\".repeat(2_000)),
840                format!("{} lead then new", "\\".repeat(2_000)),
841            ),
842        ];
843        for (old, new) in &cases {
844            for width in 0..90 {
845                let out = word_view(old, new, Some(width));
846                assert!(marks_close(&out), "width {width}: {out}");
847                // Any window wider than nothing shows the first change.
848                assert_eq!(out.contains('{'), width > 0, "width {width}: {out}");
849            }
850            assert!(marks_close(&word_view(old, new, None)));
851        }
852        // Text is cut, never a delimiter: the window counts text only.
853        assert_eq!(
854            word_view("a b", "a b c d e f g h i j", Some(10)),
855            "a b{++ c d e …++}\n"
856        );
857        assert_eq!(
858            word_view("keep one two three four five", "keep six", Some(10)),
859            "keep {~~one t…~>…~~}\n"
860        );
861        assert_eq!(
862            word_view(
863                "lead words here, then old",
864                "lead words here, then new",
865                Some(12)
866            ),
867            "… then {~~old~>new~~}\n"
868        );
869        assert_eq!(word_view("a b", "a b c d e f g h i j", Some(0)), "…\n");
870    }
871
872    #[test]
873    fn side_by_side_columns_line_up_on_every_row() {
874        let options = TextOptions {
875            format: TextFormat::SideBySide,
876            ..Default::default()
877        };
878        let view = |old: &str, new: &str| diff_text_view(old, new, &options);
879        assert_eq!(
880            view("same\nold\nend\n", "same\nnew\nend\n"),
881            "same   same\nold  | new\nend    end\n"
882        );
883        assert_eq!(
884            view("a\nlong line\n", "a\n"),
885            "a           a\nlong line <\n"
886        );
887        assert_eq!(view("a\n", "a\nadded\n"), "a   a\n  > added\n");
888        // Widths count scalars, as windows do.
889        assert_eq!(view("é界\nx\n", "é界\ny\n"), "é界   é界\nx  | y\n");
890        // An empty unchanged line leaves no trailing spaces.
891        assert_eq!(view("\nold\n", "\nnew\n"), "\nold | new\n");
892        // Whole lines pad to a default window at most; the long row alone
893        // overflows.
894        let options = TextOptions {
895            window: None,
896            ..options
897        };
898        let long = "x".repeat(200);
899        let out = diff_text_view(&format!("a\n{long}\nb\n"), "a\nb\n", &options);
900        let pad = " ".repeat(WINDOW + 1);
901        assert_eq!(out, format!("a{pad}   a\n{long} <\nb{pad}   b\n"));
902    }
903
904    #[test]
905    fn review_windows_count_scalars_and_allow_unbounded_and_zero_width() {
906        assert_eq!(clip("é界xyz", 3, Some(2)), "…xy…");
907        assert_eq!(clip("é界xyz", 0, Some(2)), "é界…");
908        assert_eq!(clip("é界xyz", 5, Some(2)), "…z");
909        assert_eq!(clip("é界xyz", 3, None), "é界xyz");
910        assert_eq!(clip("short", 100, Some(70)), "short");
911        assert_eq!(clip("abc", 0, Some(0)), "…");
912        assert_eq!(clip("abc", 1, Some(0)), "……");
913        assert_eq!(clip("", 0, Some(0)), "");
914        assert_eq!(first_difference("é界", "é中"), 1);
915        assert_eq!(first_difference("same", "same suffix"), 4);
916    }
917
918    /// A clipped window is sized from its UTF-8 bytes and ellipses once
919    /// (#4372659578, #4372904367 on #1830).
920    #[test]
921    fn a_clipped_window_is_allocated_once() {
922        for (text, at, width) in [
923            ("é界xyz", 3, 2),
924            ("界界界界界界", 3, 2),
925            ("é界xyz", 0, 2),
926            ("abc", 1, 0),
927        ] {
928            let out = clip(text, at, Some(width));
929            assert_eq!(out.capacity(), out.len(), "{text:?} at {at}: {out:?}");
930        }
931    }
932
933    #[test]
934    fn replacement_alignment_handles_inserted_and_deleted_clauses_and_large_blocks() {
935        assert_eq!(
936            replacement_rows(
937                &["Payment 30 days", "Security assets"],
938                &["Prepayment allowed", "Payment 60 days", "Security property"]
939            ),
940            [Row::Insert(0), Row::Pair(0, 1), Row::Pair(1, 2)]
941        );
942        assert_eq!(
943            replacement_rows(
944                &["Payment 60 days", "Payment 30 days"],
945                &["Payment 60 days"]
946            ),
947            [Row::Pair(0, 0), Row::Delete(1)]
948        );
949        assert_eq!(
950            replacement_rows(&["Payment stale", "Payment 30 days"], &["Payment 60 days"]),
951            [Row::Delete(0), Row::Pair(1, 0)]
952        );
953        assert_eq!(replacement_rows(&["a"], &["b"]), [Row::Pair(0, 0)]);
954        assert_eq!(replacement_rows(&["a"], &[]), [Row::Delete(0)]);
955        assert_eq!(replacement_rows(&[], &["b"]), [Row::Insert(0)]);
956        let rows = replacement_rows(&vec!["old"; 21], &vec!["new"; 22]);
957        assert_eq!(rows.len(), 22);
958        assert_eq!(rows.last(), Some(&Row::Insert(21)));
959    }
960
961    #[test]
962    fn word_changes_preserve_literal_syntax_and_changed_clause_numbers() {
963        assert_eq!(word_change("1. Terms", "2. Terms"), "{~~1~>2~~}. Terms");
964        assert_eq!(
965            word_change("pay 30 days", "pay 60 days"),
966            "pay {~~30~>60~~} days"
967        );
968        assert_eq!(word_change("", "new"), "{++new++}");
969        assert_eq!(word_change("old", ""), "{--old--}");
970        assert_eq!(word_change("same", "same"), "same");
971        // Literal markup is text, escaped.
972        assert_eq!(
973            word_change("{++literal++} old", "{++literal++} new"),
974            r"\{++literal++\} {~~old~>new~~}"
975        );
976        assert_eq!(
977            critic_literal("{+literal+}[-literal-]"),
978            "{+literal+}[-literal-]"
979        );
980        assert_eq!(critic_literal("{++literal++}"), r"\{++literal++\}");
981    }
982
983    #[test]
984    fn review_context_and_unterminated_github_lines_use_original_coordinates() {
985        let options = TextOptions {
986            window: Some(70),
987            ..Default::default()
988        };
989        assert_eq!(
990            diff_text_view("a", "b", &options),
991            diff_text("a", "b", &options.unified)
992        );
993        let options = TextOptions {
994            format: TextFormat::SideBySide,
995            ..options
996        };
997        assert_eq!(
998            diff_text_view("same\nold\nend\n", "same\nnew\nend\n", &options),
999            "same   same\nold  | new\nend    end\n"
1000        );
1001        let options = TextOptions {
1002            format: TextFormat::Context,
1003            unified: UnifiedOptions {
1004                old_name: "old\nfile".into(),
1005                new_name: "new file".into(),
1006                context: 0,
1007            },
1008            ..options
1009        };
1010        assert!(
1011            diff_text_view("a\n", "b\n", &options)
1012                .starts_with("*** \"old\\nfile\"\n--- \"new file\"\n")
1013        );
1014    }
1015
1016    #[test]
1017    fn patch_has_git_headers_ranges_and_context() {
1018        let out = diff_text(
1019            "Intro\nThirty days\nSigned\n",
1020            "Intro\nSixty days\nSigned\n",
1021            &UnifiedOptions::default(),
1022        );
1023        assert_eq!(
1024            out,
1025            "diff --git a/old.docx b/new.docx\n--- a/old.docx\n+++ b/new.docx\n@@ -1,3 +1,3 @@\n Intro\n-Thirty days\n+Sixty days\n Signed\n"
1026        );
1027    }
1028
1029    #[test]
1030    fn line_terminators_never_show_as_identical_changed_lines() {
1031        let formats = [
1032            TextFormat::Github,
1033            TextFormat::Word,
1034            TextFormat::Normal,
1035            TextFormat::Context,
1036            TextFormat::SideBySide,
1037        ];
1038        for format in formats {
1039            for window in [Some(70), None] {
1040                let options = TextOptions {
1041                    format,
1042                    window,
1043                    ..Default::default()
1044                };
1045                // CRLF against LF is the same document text.
1046                assert_eq!(
1047                    diff_text_view("one\r\ntwo\r\n", "one\ntwo\n", &options),
1048                    "",
1049                    "{format:?} {window:?}"
1050                );
1051                // A missing final newline is marked where the format has a
1052                // marker for it, and is no change where it has none.
1053                let out = diff_text_view("same", "same\n", &options);
1054                match format {
1055                    TextFormat::Github | TextFormat::Normal | TextFormat::Context => assert_eq!(
1056                        out.matches("\\ No newline at end of file").count(),
1057                        1,
1058                        "{format:?} {window:?}: {out}"
1059                    ),
1060                    TextFormat::Word | TextFormat::SideBySide => {
1061                        assert_eq!(out, "", "{format:?} {window:?}");
1062                    }
1063                }
1064            }
1065        }
1066    }
1067
1068    #[test]
1069    fn empty_ranges_and_missing_final_newlines_follow_unified_convention() {
1070        let options = UnifiedOptions {
1071            context: 0,
1072            ..Default::default()
1073        };
1074        let inserted = diff_text("", "Hello\n", &options);
1075        assert!(inserted.contains("@@ -0,0 +1 @@\n+Hello\n"), "{inserted}");
1076        let deleted = diff_text("Hello\n", "", &options);
1077        assert!(deleted.contains("@@ -1 +0,0 @@\n-Hello\n"), "{deleted}");
1078        let unterminated = diff_text("Old", "New", &options);
1079        assert_eq!(
1080            unterminated.matches("\\ No newline at end of file").count(),
1081            2
1082        );
1083    }
1084
1085    #[test]
1086    fn identical_content_has_no_patch_even_with_different_names() {
1087        assert_eq!(
1088            diff_text("same\n", "same\n", &UnifiedOptions::default()),
1089            ""
1090        );
1091        assert_eq!(diff_text("", "", &UnifiedOptions::default()), "");
1092    }
1093
1094    #[test]
1095    fn names_with_control_characters_are_git_quoted() {
1096        let options = UnifiedOptions {
1097            old_name: "a\t\".docx".into(),
1098            new_name: "b\n.docx".into(),
1099            context: 0,
1100        };
1101        let out = diff_text("a\n", "b\n", &options);
1102        assert!(
1103            out.starts_with("diff --git \"a/a\\t\\\".docx\" \"b/b\\n.docx\"\n"),
1104            "{out}"
1105        );
1106        assert!(out.contains("--- \"a/a\\t\\\".docx\"\n"));
1107    }
1108
1109    #[test]
1110    fn every_change_and_long_unicode_line_is_preserved() {
1111        let old = (0..12)
1112            .map(|n| format!("old {n} {}\n", "é".repeat(300)))
1113            .collect::<String>();
1114        let new = old.replace("old ", "new ");
1115        let out = diff_text(&old, &new, &UnifiedOptions::default());
1116        assert_eq!(out.lines().filter(|l| l.starts_with("-old ")).count(), 12);
1117        assert!(out.contains(&"é".repeat(300)));
1118        assert!(!out.contains('…'));
1119    }
1120
1121    #[test]
1122    fn word_snapshot_preserves_existing_marks_and_compares_them() {
1123        let old = word("Due in {~~30~>45~~} days.\n");
1124        let new = word("Due in {~~30~>60~~} days.\n");
1125        let snapshot = document_text(Source::Docx(&old)).unwrap();
1126        // The marks retain document order: the substitution writes its
1127        // deletion before its insertion.
1128        assert!(snapshot.contains("[-30-]{+45+}"), "{snapshot}");
1129        let out = diff_documents(
1130            Source::Docx(&old),
1131            Source::Docx(&new),
1132            &UnifiedOptions::default(),
1133        )
1134        .unwrap();
1135        assert!(out.contains("[-30-]{+45+}"), "{out}");
1136        assert!(out.contains("[-30-]{+60+}"), "{out}");
1137        assert_eq!(
1138            diff_documents(
1139                Source::Docx(&old),
1140                Source::Docx(&old),
1141                &UnifiedOptions::default()
1142            )
1143            .unwrap(),
1144            ""
1145        );
1146    }
1147
1148    #[test]
1149    fn invalid_docx_is_refused() {
1150        assert!(document_text(Source::Docx(b"not a document")).is_err());
1151    }
1152
1153    #[test]
1154    fn markdown_and_mixed_sources_share_the_same_formatter() {
1155        let old = word("Hello\n");
1156        let snapshot = document_text(Source::Docx(&old)).unwrap();
1157        assert_eq!(
1158            diff_documents(
1159                Source::Docx(&old),
1160                Source::Markdown(&snapshot),
1161                &UnifiedOptions::default()
1162            )
1163            .unwrap(),
1164            ""
1165        );
1166        assert!(
1167            diff_documents(
1168                Source::Markdown("Old\n"),
1169                Source::Markdown("New\n"),
1170                &UnifiedOptions::default()
1171            )
1172            .unwrap()
1173            .contains("-Old\n+New\n")
1174        );
1175    }
1176}