Skip to main content

jubarte_edit/markdown/
unified.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! The changes between two documents as a git-style patch.
6//!
7//! ```text
8//! --- a/agreement.md
9//! +++ b/agreement.md<TAB>Arthur Rodrigues<TAB>2026-09-30T14:05:00Z
10//! @@ [line:3] @@
11//! Closing on [-04/20/26-]{+10/30/26+}{>>Arthur Rodrigues (2026-09-30T14:05:00Z): Financing.<<}.
12//! ```
13//!
14//! Only the paragraphs that changed are shown, each whole, under the place it
15//! has in the new version (`@@ [line:3] @@`), or in the old one when it was
16//! removed (`@@ -[line:7] @@`). Deleted text is `[-...-]` and inserted text
17//! `{+...+}`, as `git diff --word-diff` writes them; highlights and comments
18//! stay CriticMarkup (`{==...==}`, `{>>...<<}`). The document owner and the
19//! date of the patch are on the `+++` line, after tabs; a change by anyone else, or at
20//! another time, is followed by its author and date (`{>>Name (date)<<}`),
21//! and every comment names its author and date.
22//!
23//! The text is wrapped at [`DEFAULT_COLUMNS`], only at spaces, and never
24//! where the break would change the Markdown: inside a code span or a link
25//! target, after a backslash, before a list, heading, quote or table marker,
26//! or in a heading, table row or code block.
27
28use std::collections::{HashMap, HashSet};
29use std::fmt;
30
31use super::critic::{self, Piece, Token};
32use super::diff::{continues, diff_markdown, marker_len, open_paragraph, table_row};
33use super::redline::{RedlineOptions, Source, redline};
34use super::write::named;
35use super::{MarkdownError, MarkdownOptions, docx_to_markdown, docx_to_markdown_stories};
36use crate::document_comparer::{accept_revisions, reject_revisions};
37use crate::inspect;
38
39/// The column width the [`Patch`] display formatter wraps to; passed to
40/// [`Patch::render`] as `columns` to change it.
41pub const DEFAULT_COLUMNS: usize = 72;
42
43/// The author and date of a change or comment, in the form Word writes and
44/// jubarte's Markdown edit path encodes (`YYYY-MM-DDTHH:MM:SSZ`).
45#[derive(Clone, Debug, PartialEq, Eq)]
46pub struct Attribution {
47    /// The name Word shows.
48    pub author: String,
49    /// `YYYY-MM-DDTHH:MM:SSZ` (ISO 8601 down to the second, UTC offset
50    /// `Z` by default).
51    pub date: String,
52}
53
54/// The names written on the patch's `---` and `+++` header lines, and
55/// the document owner (the author and date of every change and comment
56/// that names none).
57#[derive(Clone, Debug, PartialEq, Eq)]
58pub struct PatchOptions {
59    /// The old document's name, after `--- a/`.
60    pub old_name: String,
61    /// The new document's name, after `+++ b/`.
62    pub new_name: String,
63    /// Author and date of every change and comment that names none.
64    pub owner: Attribution,
65}
66
67/// Where a hunk's paragraph is.
68#[derive(Clone, Debug, PartialEq, Eq)]
69pub enum Locator {
70    /// The 1-based line of a Markdown document.
71    Line(usize),
72    /// A paragraph of a Word document by the id an edit plan names it by:
73    /// `p3`, `footnotes.p1` ([`crate::ids::paragraph_id`]).
74    Paragraph {
75        /// `body`, or the part a header, footer or note is in
76        /// (`header1`, `footnotes`).
77        story: String,
78        /// Its 0-based order in the story.
79        index: usize,
80    },
81}
82
83impl fmt::Display for Locator {
84    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85        match self {
86            Self::Line(line) => write!(f, "line:{line}"),
87            Self::Paragraph { story, index } => {
88                f.write_str(&crate::ids::paragraph_id(story, *index))
89            }
90        }
91    }
92}
93
94/// A comment, on a change, on highlighted text, or at a point.
95#[derive(Clone, Debug, PartialEq, Eq)]
96pub struct Comment {
97    /// The author name (Word's `w:author`).
98    pub author: String,
99    /// `YYYY-MM-DDTHH:MM:SSZ`, the date Word writes.
100    pub date: String,
101    /// The comment text: everything after `Name (date):`, or empty for an
102    /// attribution alone (`{>>Name (date)<<}`).
103    pub text: String,
104    /// The highlighted text the comment is on (when the comment was on a
105    /// `{==…==}` highlight), or `None` for a comment on a tracked change
106    /// or a free-standing comment.
107    pub on: Option<String>,
108}
109
110/// One tracked change (or self-contained substitution), with its author
111/// and date. `old` and `new` are both nonempty for a substitution, only
112/// `old` for a deletion, only `new` for an insertion.
113#[derive(Clone, Debug, PartialEq, Eq)]
114pub struct Change {
115    /// The text deleted (empty for an insertion).
116    pub old: String,
117    /// The text inserted (empty for a deletion).
118    pub new: String,
119    /// Who made the change (the change's own author, when it names one;
120    /// otherwise the [`PatchOptions::owner`]).
121    pub author: String,
122    /// When the change was made.
123    pub date: String,
124    /// The comment written right after the change, if any.
125    pub comment: Option<Comment>,
126}
127
128/// One changed paragraph: its [`Locator`] (where it is in the old or new
129/// document), whether it is removed (a paragraph only in the old
130/// version), its rendered text with markup intact, its changes in order,
131/// and any comments that were not written right after a change.
132#[derive(Clone, Debug, PartialEq, Eq)]
133pub struct Hunk {
134    /// The paragraph in the new version, or in the old one when `removed`.
135    pub at: Locator,
136    /// The paragraph is not in the new version.
137    pub removed: bool,
138    /// The paragraph with its markup, unwrapped.
139    pub text: String,
140    /// The changes, in order.
141    pub changes: Vec<Change>,
142    /// Comments not written right after a change.
143    pub comments: Vec<Comment>,
144}
145
146/// The changed paragraphs of a document, as a `git diff --word-diff`
147/// patch. Displayed, it is [`render`](Self::render)ed at
148/// [`DEFAULT_COLUMNS`].
149#[derive(Clone, Debug, PartialEq, Eq)]
150pub struct Patch {
151    /// The old document's name.
152    pub old_name: String,
153    /// The new document's name.
154    pub new_name: String,
155    /// Author and date of the changes and comments that name none.
156    pub owner: Attribution,
157    /// The changed paragraphs, in document order.
158    pub hunks: Vec<Hunk>,
159}
160
161impl Patch {
162    /// Renders the patch as text, wrapped at `columns` (`0` does not
163    /// wrap). Returns an empty string when nothing changed.
164    pub fn render(&self, columns: usize) -> String {
165        if self.hunks.is_empty() {
166            return String::new();
167        }
168        let mut out = format!(
169            "--- a/{}\n+++ b/{}\t{}\t{}\n",
170            path_name(&self.old_name),
171            path_name(&self.new_name),
172            self.owner.author,
173            self.owner.date
174        );
175        for (index, hunk) in self.hunks.iter().enumerate() {
176            if index > 0 {
177                out.push('\n');
178            }
179            let sign = if hunk.removed { "-" } else { "" };
180            out.push_str(&format!("@@ {sign}[{}] @@\n", hunk.at));
181            out.push_str(&wrap(&hunk.text, columns));
182            out.push('\n');
183        }
184        out
185    }
186}
187
188impl fmt::Display for Patch {
189    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
190        f.write_str(&self.render(DEFAULT_COLUMNS))
191    }
192}
193
194/// A file name as `git diff` shows it after `a/`: without `./` or `/`.
195fn path_name(name: &str) -> &str {
196    let name = name.strip_prefix("./").unwrap_or(name);
197    name.trim_start_matches('/')
198}
199
200/// Diffs two Markdown documents (`old`, `new`) as a single [`Patch`]
201/// whose changes are attributed to the [`PatchOptions::owner`]. Each
202/// hunk lives at the line its paragraph starts on in the document
203/// itself.
204///
205/// Backs `jubarte diff old.md new.md` (`--format critic`, or the unified
206/// patch `--format`/`patch` when both inputs are Markdown).
207///
208/// ```
209/// use jubarte_edit::markdown::{Attribution, PatchOptions, patch_markdown};
210///
211/// let options = PatchOptions {
212///     old_name: "a.md".into(),
213///     new_name: "b.md".into(),
214///     owner: Attribution { author: "Ana".into(), date: "2026-09-30T14:05:00Z".into() },
215/// };
216/// let patch = patch_markdown("Due in 30 days.\n", "Due in 45 days.\n", &options);
217/// assert_eq!(
218///     patch.to_string(),
219///     "--- a/a.md\n+++ b/b.md\tAna\t2026-09-30T14:05:00Z\n@@ [line:1] @@\nDue in [-30-]{+45+} days.\n"
220/// );
221/// ```
222pub fn patch_markdown(old: &str, new: &str, options: &PatchOptions) -> Patch {
223    let (mut patch, texts) = build(&diff_markdown(old, new), options);
224    // Each hunk at the line its paragraph starts on in the document itself,
225    // found in order; where it is not found (text the diff escaped), the
226    // line counted from the markup stays.
227    let lines = |text: &str| -> Vec<String> {
228        text.replace("\r\n", "\n")
229            .lines()
230            .map(str::to_string)
231            .collect()
232    };
233    let (old_lines, new_lines) = (lines(old), lines(new));
234    let (mut old_from, mut new_from) = (0, 0);
235    let texts = texts.into_iter().filter(|t| t.hunk.is_some());
236    for (
237        hunk,
238        Paragraphs {
239            old: old_text,
240            new: new_text,
241            ..
242        },
243    ) in patch.hunks.iter_mut().zip(texts)
244    {
245        let (text, lines, from) = if hunk.removed {
246            (old_text, &old_lines, &mut old_from)
247        } else {
248            (new_text, &new_lines, &mut new_from)
249        };
250        let first = text.trim_start_matches('\n').lines().next().unwrap_or("");
251        if first.is_empty() {
252            continue;
253        }
254        if let Some(found) = lines[(*from).min(lines.len())..]
255            .iter()
256            .position(|l| l == first)
257        {
258            let line = *from + found;
259            hunk.at = Locator::Line(line + 1);
260            *from = line + 1;
261        }
262    }
263    patch
264}
265
266/// Builds a [`Patch`] from a Markdown document whose CriticMarkup holds
267/// the changes (as [`diff_markdown`] or [`docx_to_markdown`] write it).
268///
269/// # Attribution rules
270///
271/// - `{r1 Name (date)}` immediately after a change is its author and date.
272///   A substitution tag names its deletion then insertion. `¶{r1 Name}`
273///   attributes the following inserted paragraph separator.
274/// - `{>>Name (date): text<<}` is a comment by `Name`, attached to the
275///   preceding change (or to a highlight, depending on the context).
276/// - Every other comment, and every change without an author, is the
277///   [`PatchOptions::owner`]'s.
278pub fn patch_critic(critic: &str, options: &PatchOptions) -> Patch {
279    build(critic, options).0
280}
281
282/// A Word redline's tracked changes and comments as a patch, each hunk at
283/// the id ([`pN`](Locator::Paragraph)) [`jubarte::inspect`](crate::inspect) gives its
284/// paragraph once every change is accepted (or rejected, for a removed
285/// paragraph): the id an edit plan names it by. A change in a text box is
286/// at the paragraph that holds the box. Every comment is shown.
287pub fn patch_redline(docx: &[u8], options: &PatchOptions) -> Result<Patch, MarkdownError> {
288    let package = |error: crate::opc::OpcError| MarkdownError::Package(error.to_string());
289    let old = reject_revisions(docx).map_err(package)?;
290    let new = accept_revisions(docx).map_err(package)?;
291    patch_word(docx, &old, &new, None, options, &MarkdownOptions::default())
292}
293
294/// [`patch_redline`] for the owner's own changes: every change by
295/// another author, or by the owner on another date, is accepted first,
296/// so the patch reads as only the changes still attributed to the
297/// owner. An edit plan with
298/// [`existing_revisions: "keep"`](crate::edit::ExistingRevisions) writes
299/// its patch this way, beside the other party's tracked changes.
300///
301/// # Errors
302///
303/// - [`MarkdownError::Docx`] when the package's tracked changes cannot
304///   be listed (admission refusal, package read failure, or malformed
305///   part).
306/// - [`MarkdownError::Package`] when accepting the other-party
307///   revisions or accepting / rejecting every revision afterward fails.
308pub fn patch_own_changes(docx: &[u8], options: &PatchOptions) -> Result<Patch, MarkdownError> {
309    let changes = crate::changes::list_changes(docx)
310        .map_err(|error| MarkdownError::Docx(error.to_string()))?;
311    let others: Vec<String> = changes
312        .into_iter()
313        .filter(|c| {
314            c.author.as_deref() != Some(options.owner.author.as_str())
315                || c.date.as_deref() != Some(options.owner.date.as_str())
316        })
317        .map(|c| c.id)
318        .collect();
319    if others.is_empty() {
320        return patch_redline(docx, options);
321    }
322    let filter = crate::changes::ChangeFilter {
323        ids: Some(others),
324        ..crate::changes::ChangeFilter::default()
325    };
326    let own = crate::changes::accept_elements(docx, &filter)
327        .map_err(|error| MarkdownError::Package(error.to_string()))?;
328    patch_redline(&own, options)
329}
330
331/// The changes from `old` to `new` as a patch. Two Markdown documents give
332/// [`patch_markdown`]'s patch, at lines; otherwise the documents are
333/// compared as [`redline`] compares them and each hunk is at a `pN`
334/// of the Word document on its side (of the redline, accepted or rejected,
335/// where that side is Markdown). The comparer's changes are the owner's;
336/// a comment the old document has too is not a change.
337pub fn patch_documents(
338    old: Source<'_>,
339    new: Source<'_>,
340    redline_options: &RedlineOptions<'_>,
341    options: &PatchOptions,
342) -> Result<Patch, MarkdownError> {
343    if let (Source::Markdown(old), Source::Markdown(new)) = (old, new) {
344        return Ok(patch_markdown(old, new, options));
345    }
346    let mut compared = redline_options.clone();
347    compared.settings.author_for_revisions = options.owner.author.clone();
348    compared.settings.date_time_for_revisions = options.owner.date.clone();
349    let docx = redline(old, new, &compared)?;
350    let package = |error: crate::opc::OpcError| MarkdownError::Package(error.to_string());
351    let old = match old {
352        Source::Docx(docx) => docx.to_vec(),
353        Source::Markdown(_) => reject_revisions(&docx).map_err(package)?,
354    };
355    let new = match new {
356        Source::Docx(docx) => docx.to_vec(),
357        Source::Markdown(_) => accept_revisions(&docx).map_err(package)?,
358    };
359    let markdown_options = MarkdownOptions {
360        input_limits: compared.settings.input_limits,
361        ..MarkdownOptions::default()
362    };
363    let known = segments(&docx_to_markdown(&old, &markdown_options)?.markdown)
364        .into_iter()
365        .filter_map(|segment| match segment {
366            Segment::Note(note, _) => Some(note),
367            _ => None,
368        })
369        .collect();
370    patch_word(&docx, &old, &new, Some(&known), options, &markdown_options)
371}
372
373/// The redline's patch with each hunk at the paragraph of `old` or `new`
374/// its text is, found in order.
375fn patch_word(
376    docx: &[u8],
377    old: &[u8],
378    new: &[u8],
379    known: Option<&HashSet<String>>,
380    options: &PatchOptions,
381    markdown_options: &MarkdownOptions,
382) -> Result<Patch, MarkdownError> {
383    let critic = docx_to_markdown_stories(docx, markdown_options)?.markdown;
384    let (mut patch, texts) = build_with(&critic, options, known);
385    let (old, new) = (
386        word_paragraphs(old, markdown_options.input_limits)?,
387        word_paragraphs(new, markdown_options.input_limits)?,
388    );
389    // Every paragraph is looked for, changed or not, so the search follows
390    // the document; text found in no paragraph is in a text box, and goes
391    // to the paragraph found last, the one that holds the box.
392    let mut sides = [Search::new(&old), Search::new(&new)];
393    for block in texts {
394        let old_at = sides[0].next(&block.old);
395        let new_at = sides[1].next(&block.new);
396        if let Some(hunk) = block.hunk.and_then(|i| patch.hunks.get_mut(i)) {
397            let at = if hunk.removed { old_at } else { new_at };
398            if let Some(at) = at {
399                hunk.at = at;
400            }
401        }
402    }
403    Ok(patch)
404}
405
406/// A Word paragraph as [`patch_word`] looks for it.
407struct WordParagraph {
408    at: Locator,
409    letters: String,
410}
411
412/// The paragraphs of one version, looked for in order.
413struct Search<'a> {
414    letters: Vec<&'a str>,
415    paragraphs: &'a [WordParagraph],
416    /// Where the search goes on from.
417    next: usize,
418    /// The paragraph found last.
419    last: usize,
420}
421
422impl<'a> Search<'a> {
423    fn new(paragraphs: &'a [WordParagraph]) -> Self {
424        Self {
425            letters: paragraphs.iter().map(|p| p.letters.as_str()).collect(),
426            paragraphs,
427            next: 0,
428            last: 0,
429        }
430    }
431
432    /// Where a block with this Markdown is: the next paragraph with its
433    /// text, else the one found last. `None` when the block has no text in
434    /// this version, or the document no paragraphs.
435    fn next(&mut self, markdown: &str) -> Option<Locator> {
436        if !visible(markdown) {
437            return None;
438        }
439        if let Some(found) = find(&letters(&plain(markdown)), &self.letters, self.next) {
440            self.next = found + 1;
441            self.last = found;
442        }
443        self.paragraphs.get(self.last).map(|p| p.at.clone())
444    }
445}
446
447/// The body's paragraphs, then the headers', footers' and notes', as
448/// `jubarte text` lists them.
449fn word_paragraphs(
450    docx: &[u8],
451    limits: crate::admission::InputLimits,
452) -> Result<Vec<WordParagraph>, MarkdownError> {
453    let error = |error: inspect::InspectError| MarkdownError::Docx(error.to_string());
454    let (body, stories) = inspect::paragraphs_and_stories_within(docx, limits).map_err(error)?;
455    let all = body.into_iter().map(|p| ("body".to_string(), p)).chain(
456        stories
457            .into_iter()
458            .flat_map(|s| s.paragraphs.into_iter().map(move |p| (s.id.clone(), p))),
459    );
460    Ok(all
461        .map(|(story, p)| WordParagraph {
462            at: Locator::Paragraph {
463                story,
464                index: p.index,
465            },
466            letters: letters(&p.text),
467        })
468        .collect())
469}
470
471/// The first paragraph from `from` on whose text is the block's, else one
472/// the block holds (a table row's cell, a paragraph and the one joined to
473/// it, a list item's text after its number).
474fn find(block: &str, paragraphs: &[&str], from: usize) -> Option<usize> {
475    let rest = paragraphs.get(from..)?;
476    let at = |test: &dyn Fn(&str) -> bool| {
477        rest.iter()
478            .position(|p| !p.is_empty() && test(p))
479            .map(|i| from + i)
480    };
481    at(&|p| p == block).or_else(|| at(&|p| block.contains(p)))
482}
483
484/// Letters and digits only.
485fn letters(text: &str) -> String {
486    text.chars().filter(|c| c.is_alphanumeric()).collect()
487}
488
489/// Markdown without what a paragraph's text does not have: the list or
490/// heading marker, link and image targets, footnote references and HTML
491/// tags.
492fn plain(markdown: &str) -> String {
493    let markdown = markdown.trim_start_matches('\n');
494    let mut out = String::new();
495    let mut rest = &markdown[marker_len(markdown)..];
496    while let Some(c) = rest.chars().next() {
497        let skip = if rest.starts_with("](") {
498            out.push(']');
499            rest.find(')').map(|end| end + 1)
500        } else if rest.starts_with("[^") {
501            rest.find(']').map(|end| end + 1)
502        } else if c == '<' && rest[1..].starts_with(|c: char| c.is_ascii_alphabetic() || c == '/') {
503            rest.find('>').map(|end| end + 1)
504        } else {
505            None
506        };
507        match skip {
508            Some(length) => rest = &rest[length..],
509            None => {
510                out.push(c);
511                rest = &rest[c.len_utf8()..];
512            }
513        }
514    }
515    out
516}
517
518/// A block's text in the old and new versions, and its hunk if it has one.
519struct Paragraphs {
520    hunk: Option<usize>,
521    old: String,
522    new: String,
523}
524
525/// The patch, with every block's text in the old and new versions.
526fn build(critic: &str, options: &PatchOptions) -> (Patch, Vec<Paragraphs>) {
527    build_with(critic, options, None)
528}
529
530/// [`build`], where a paragraph whose only marks are highlights and
531/// comments in `known` (the old document's) is not a hunk.
532fn build_with(
533    critic: &str,
534    options: &PatchOptions,
535    known: Option<&HashSet<String>>,
536) -> (Patch, Vec<Paragraphs>) {
537    let critic = critic.replace("\r\n", "\n");
538    let owner = &options.owner;
539    // Only the front matter holds the table: a body paragraph that looks
540    // like one names no one.
541    let authors = super::write::split_front_matter(&critic)
542        .map(|(yaml, _)| super::view_notes::authors(yaml))
543        .unwrap_or_default();
544    let blocks = blocks(detach_breaks(join_marks(attribute(
545        segments(&critic),
546        &authors,
547        owner,
548    ))));
549    let mut hunks = Vec::new();
550    let mut texts = Vec::new();
551    let (mut old_line, mut new_line) = (1, 1);
552    for block in &blocks {
553        old_line += newlines(&block.separator, block.old_before_visible);
554        new_line += newlines(&block.separator, block.new_before_visible);
555        let (old_text, new_text) = (block.text(Side::Old), block.text(Side::New));
556        if block.marked(known) {
557            let (at, removed) = if visible(&new_text) || !visible(&old_text) {
558                (Locator::Line(new_line), false)
559            } else {
560                (Locator::Line(old_line), true)
561            };
562            texts.push(Paragraphs {
563                hunk: Some(hunks.len()),
564                old: old_text.clone(),
565                new: new_text.clone(),
566            });
567            hunks.push(hunk(block, at, removed, owner));
568        } else {
569            texts.push(Paragraphs {
570                hunk: None,
571                old: old_text.clone(),
572                new: new_text.clone(),
573            });
574        }
575        old_line += old_text.matches('\n').count();
576        new_line += new_text.matches('\n').count();
577    }
578    let patch = Patch {
579        old_name: options.old_name.clone(),
580        new_name: options.new_name.clone(),
581        owner: owner.clone(),
582        hunks,
583    };
584    (patch, texts)
585}
586
587fn newlines(separator: &str, counted: bool) -> usize {
588    if counted {
589        separator.matches('\n').count()
590    } else {
591        0
592    }
593}
594
595#[derive(Clone, Copy, PartialEq, Eq)]
596enum Side {
597    Old,
598    New,
599}
600
601/// Deleted and inserted text: `plain` without the markup nested in it,
602/// `marked` with it.
603#[derive(Clone, Debug, Default)]
604struct Edit {
605    old: String,
606    new: String,
607    old_marked: String,
608    new_marked: String,
609    by: Option<(String, String)>,
610    /// The insertion's own author and date, when a substitution's sides
611    /// were made by two authors (the view names them old then new).
612    new_by: Option<(String, String)>,
613}
614
615impl Edit {
616    fn push(&mut self, side: Side, text: &str, plain: bool) {
617        let (plain_text, marked) = match side {
618            Side::Old => (&mut self.old, &mut self.old_marked),
619            Side::New => (&mut self.new, &mut self.new_marked),
620        };
621        if plain {
622            plain_text.push_str(text);
623        }
624        marked.push_str(text);
625    }
626}
627
628#[derive(Clone, Debug)]
629enum Segment {
630    Same(String),
631    Edit(Edit),
632    HighlightStart,
633    HighlightEnd,
634    /// A comment's text, as written.
635    Note(String, bool),
636}
637
638/// The document as text, changes, highlight delimiters and comments.
639fn segments(critic: &str) -> Vec<Segment> {
640    let mut out: Vec<Segment> = Vec::new();
641    let mut edit: Option<Edit> = None;
642    let mut side = Side::New;
643    let mut note: Option<String> = None;
644    let mut attribution = false;
645    let mut paragraph_note = false;
646    // A ¶ tag attributes the next paragraph separator, not the preceding text.
647    let mut paragraph_break: Option<(String, String)> = None;
648    // Comments that end inside a change, written after it.
649    let mut held: Vec<String> = Vec::new();
650    critic::Pieces::default().feed(&critic::encode_spans_only(critic), |piece| match piece {
651        Piece::Text(mut text) => {
652            if let Some((tag, mut separator)) = paragraph_break.take() {
653                while separator.bytes().filter(|&b| b == b'\n').count() < 2 {
654                    let width = if text.starts_with("\r\n") {
655                        2
656                    } else if text.starts_with('\n') {
657                        1
658                    } else {
659                        break;
660                    };
661                    separator.push_str(&text[..width]);
662                    text = &text[width..];
663                }
664                if separator.bytes().filter(|&b| b == b'\n').count() == 2 {
665                    let mut boundary = Edit::default();
666                    boundary.push(Side::New, &separator, true);
667                    out.push(Segment::Edit(boundary));
668                    out.push(Segment::Note(tag, true));
669                } else if text.is_empty() {
670                    paragraph_break = Some((tag, separator));
671                } else {
672                    push_same(&mut out, &separator);
673                }
674                if text.is_empty() {
675                    return;
676                }
677            }
678            if let Some(note) = &mut note {
679                note.push_str(text);
680            } else if let Some(edit) = &mut edit {
681                edit.push(side, text, true);
682            } else if let Some(Segment::Same(same)) = out.last_mut() {
683                same.push_str(text);
684            } else {
685                out.push(Segment::Same(text.to_string()));
686            }
687        }
688        Piece::Token(token) => match token {
689            // A highlight run or a field is Markdown text, not a change.
690            Token::MarkStart
691            | Token::MarkEnd
692            | Token::FieldStart
693            | Token::FieldSeparator
694            | Token::FieldEnd => {
695                let text = critic::delimiter(token);
696                if let Some(note) = &mut note {
697                    note.push_str(text);
698                } else if let Some(edit) = &mut edit {
699                    edit.push(side, text, false);
700                } else {
701                    push_same(&mut out, text);
702                }
703            }
704            Token::InsertStart | Token::DeleteStart | Token::SubstituteStart => {
705                edit = Some(Edit::default());
706                side = if token == Token::InsertStart {
707                    Side::New
708                } else {
709                    Side::Old
710                };
711            }
712            Token::SubstituteSeparator => side = Side::New,
713            Token::InsertEnd | Token::DeleteEnd | Token::SubstituteEnd => {
714                if let Some(edit) = edit.take() {
715                    out.push(Segment::Edit(edit));
716                }
717                out.extend(held.drain(..).map(|text| Segment::Note(text, false)));
718            }
719            Token::HighlightStart | Token::HighlightEnd => {
720                let start = token == Token::HighlightStart;
721                match &mut edit {
722                    Some(edit) => edit.push(side, if start { "{==" } else { "==}" }, false),
723                    None if start => out.push(Segment::HighlightStart),
724                    None => out.push(Segment::HighlightEnd),
725                }
726            }
727            Token::CommentStart | Token::AttributionStart | Token::ParagraphInsertion => {
728                attribution = token != Token::CommentStart;
729                paragraph_note = token == Token::ParagraphInsertion;
730                note = Some(String::new());
731            }
732            // A comment paragraph break, inside a note or in dropped
733            // text.
734            Token::CommentBreak => {
735                if let Some(note) = &mut note {
736                    note.push_str("\n\n");
737                }
738            }
739            Token::CommentEnd | Token::AttributionEnd => {
740                let text = note.take().unwrap_or_default();
741                if std::mem::take(&mut paragraph_note) {
742                    paragraph_break = Some((text, String::new()));
743                    return;
744                }
745                if edit.is_some() {
746                    held.push(text);
747                } else {
748                    out.push(Segment::Note(text, attribution));
749                }
750            }
751        },
752    });
753    if let Some((_, separator)) = paragraph_break {
754        push_same(&mut out, &separator);
755    }
756    out
757}
758
759/// `Name (date)` in the comment right after a change, or after the
760/// comments that follow it, becomes the change's author and date; so does
761/// the plain view's numbered note (`r3 Name (date)`), whose number says it
762/// names the change. A number alone names no one: the owner made it.
763/// An agent tag (`r1 @A`) names the person in the document's `authors:`
764/// table, or the patch owner when that handle is absent, and is not a
765/// comment; a nested one (`r3 @BO re r1 @AL`) names the change by its
766/// first tag. A substitution whose sides two authors made is followed by
767/// two such notes, the deletion's then the insertion's.
768fn attribute(
769    segments: Vec<Segment>,
770    authors: &HashMap<String, super::view_notes::Author>,
771    owner: &Attribution,
772) -> Vec<Segment> {
773    let mut out: Vec<Segment> = Vec::with_capacity(segments.len());
774    // Whether the last edit has taken its (first) note.
775    let mut named_edit = false;
776    // The side of the last edit an undated tag of an author dated
777    // `first..last` named, by handle: it takes the last day at the end.
778    let mut ranged: HashMap<String, (usize, Side)> = HashMap::new();
779    for segment in segments {
780        // Where the edit a note names sits: the last segment before it that
781        // is no note.
782        let at = out
783            .iter()
784            .rposition(|s| !matches!(s, Segment::Note(..)))
785            .unwrap_or_default();
786        if let Segment::Note(text, true) = &segment
787            && let Some(Segment::Edit(edit)) = out
788                .iter_mut()
789                .rev()
790                .find(|s| !matches!(s, Segment::Note(..)))
791        {
792            if let Some(parts) = super::view_notes::plain_revisions(text.trim())
793                && parts.len() == 2
794                && !edit.old_marked.is_empty()
795                && !edit.new_marked.is_empty()
796            {
797                let by = |part: &super::view_notes::PlainRevision| {
798                    (!part.author.is_empty() || !part.date.is_empty())
799                        .then(|| (part.author.clone(), part.date.clone()))
800                };
801                edit.by = by(&parts[0]);
802                edit.new_by = by(&parts[1]);
803                named_edit = true;
804                continue;
805            }
806            if let Some(tags) = super::view_notes::revision_tags(text.trim()).or_else(|| {
807                super::view_notes::nested_revision_tags(text.trim())
808                    .map(|nest| nest.into_iter().take(1).collect())
809            }) && let Some(first) = tags.first()
810            {
811                let mut range = |tag: &super::view_notes::Tag, side: Side| {
812                    if tag.date.is_none() && authors.get(&tag.handle).is_some_and(ranged_only) {
813                        ranged.insert(tag.handle.clone(), (at, side));
814                    }
815                };
816                let both_sides = !edit.old_marked.is_empty() && !edit.new_marked.is_empty();
817                if tags.len() == 2 && both_sides {
818                    edit.by = Some(tag_attribution(&tags[0], authors, owner));
819                    edit.new_by = Some(tag_attribution(&tags[1], authors, owner));
820                    range(&tags[0], Side::Old);
821                    range(&tags[1], Side::New);
822                    named_edit = true;
823                    continue;
824                }
825                let resolved = Some(tag_attribution(first, authors, owner));
826                if !named_edit || (!both_sides && edit.by.is_none()) {
827                    edit.by = resolved;
828                    // One tag on a substitution: the deletion is the mark
829                    // written last, as the reader writes the insertion
830                    // first.
831                    range(
832                        first,
833                        if edit.old_marked.is_empty() {
834                            Side::New
835                        } else {
836                            Side::Old
837                        },
838                    );
839                    named_edit = true;
840                    continue;
841                }
842                if both_sides && edit.new_by.is_none() {
843                    edit.new_by = resolved;
844                    range(first, Side::New);
845                    continue;
846                }
847            }
848            let by = if let Some(plain) = super::view_notes::plain_revision(text.trim()) {
849                Some(
850                    (!plain.author.is_empty() || !plain.date.is_empty())
851                        .then_some((plain.author, plain.date)),
852                )
853            } else if let Some((Some(author), date, "")) = named(text.trim()) {
854                Some(Some((author, date.to_string())))
855            } else {
856                None
857            };
858            if let Some(by) = by {
859                let both_sides = !edit.old_marked.is_empty() && !edit.new_marked.is_empty();
860                // A note that names no one (`r3`) leaves a one-sided change
861                // to the next note that does.
862                if !named_edit || (!both_sides && edit.by.is_none()) {
863                    edit.by = by;
864                    named_edit = true;
865                    continue;
866                }
867                if both_sides && edit.new_by.is_none() && by.is_some() {
868                    edit.new_by = by;
869                    continue;
870                }
871            }
872        }
873        if matches!(segment, Segment::Edit(_)) {
874            named_edit = false;
875        }
876        out.push(segment);
877    }
878    for (handle, (at, side)) in ranged {
879        let Some((_, last)) = authors.get(&handle).and_then(|known| known.range.as_ref()) else {
880            continue;
881        };
882        let Some(Segment::Edit(edit)) = out.get_mut(at) else {
883            continue;
884        };
885        let last = format!("{last}T23:59:59Z");
886        let both_sides = !edit.old_marked.is_empty() && !edit.new_marked.is_empty();
887        match side {
888            Side::New if both_sides => {
889                if let Some((_, date)) = &mut edit.new_by {
890                    *date = last;
891                }
892            }
893            Side::Old if both_sides && edit.new_by.is_none() => {
894                // The insertion keeps the first day; the deletion takes
895                // the last.
896                edit.new_by = edit.by.clone();
897                if let Some((_, date)) = &mut edit.by {
898                    *date = last;
899                }
900            }
901            _ => {
902                if let Some((_, date)) = &mut edit.by {
903                    *date = last;
904                }
905            }
906        }
907    }
908    out
909}
910
911/// Whether an author row dates its marks only by a range of days
912/// (`2026-03-02..2026-03-04`), with no single date or latest one.
913fn ranged_only(known: &super::view_notes::Author) -> bool {
914    known.range.is_some() && known.date.is_none() && known.latest.is_none()
915}
916
917/// Who an agent tag names, as the view reader reads it: the `authors:` row
918/// for its handle, `??` no one, and the patch owner a handle the table
919/// lacks. A date on the tag wins; otherwise the row's date, latest date or
920/// first day of its range. A known row with none of them leaves the change
921/// undated; only an unknown handle takes the owner's date.
922fn tag_attribution(
923    tag: &super::view_notes::Tag,
924    authors: &HashMap<String, super::view_notes::Author>,
925    owner: &Attribution,
926) -> (String, String) {
927    let known = authors.get(&tag.handle);
928    let author = match known {
929        _ if tag.handle == super::view_notes::UNNAMED => String::new(),
930        Some(person) => person.name.clone(),
931        None => owner.author.clone(),
932    };
933    if let Some(date) = &tag.date {
934        return (author, date.clone());
935    }
936    let date = match known {
937        Some(person) => person
938            .date
939            .clone()
940            .or_else(|| person.latest.clone())
941            .or_else(|| {
942                person
943                    .range
944                    .as_ref()
945                    .map(|(first, _)| format!("{first}T00:00:00Z"))
946            })
947            .unwrap_or_default(),
948        None if tag.handle == super::view_notes::UNNAMED => String::new(),
949        None => owner.date.clone(),
950    };
951    (author, date)
952}
953
954/// The side a one-sided change is on, and whether it is only paragraph
955/// marks.
956fn one_side(edit: &Edit) -> Option<(Side, bool)> {
957    match (edit.old.is_empty(), edit.new.is_empty()) {
958        (false, true) => Some((Side::Old, edit.old.trim().is_empty())),
959        (true, false) => Some((Side::New, edit.new.trim().is_empty())),
960        _ => None,
961    }
962}
963
964/// The view writes a paragraph mark's change apart from the text beside
965/// it, each with its own id (#1135). Word made them as one, so the patch
966/// reads them as one: a change on the same side by the same author, with
967/// only comments between, joins the change before it when either is the
968/// mark. A paragraph deleted whole is then one change ending in its mark,
969/// and a deletion across paragraphs one change through the mark.
970fn join_marks(segments: Vec<Segment>) -> Vec<Segment> {
971    let mut out: Vec<Segment> = Vec::with_capacity(segments.len());
972    for segment in segments {
973        if let Segment::Edit(edit) = &segment
974            && let Some((side, mark)) = one_side(edit)
975            && let Some(Segment::Edit(before)) = out
976                .iter_mut()
977                .rev()
978                .find(|s| !matches!(s, Segment::Note(..)))
979            && let Some((before_side, _)) = one_side(before)
980            && before_side == side
981            && before.by == edit.by
982            && (mark
983                || match side {
984                    Side::Old => before.old.ends_with('\n'),
985                    Side::New => before.new.ends_with('\n'),
986                })
987        {
988            match side {
989                Side::Old => {
990                    before.old.push_str(&edit.old);
991                    before.old_marked.push_str(&edit.old_marked);
992                }
993                Side::New => {
994                    before.new.push_str(&edit.new);
995                    before.new_marked.push_str(&edit.new_marked);
996                }
997            }
998            continue;
999        }
1000        out.push(segment);
1001    }
1002    out
1003}
1004
1005/// Word deletes or inserts a paragraph with its mark, so the change ends
1006/// with the paragraph break (or, for the last paragraph, starts with the
1007/// one before it). That break moves out of the change, after its comments,
1008/// so the paragraph is a block of its own. A change that is only a break
1009/// joins or splits paragraphs and stays as it is, unless it leads a
1010/// paragraph the same side changes whole: the view writes a story's last
1011/// paragraph and the mark before it as two changes (`{--\n\n--}{r1
1012/// @C}{--Last.--}{r2 @C}`), and the paragraph is still a hunk of its own.
1013/// A change that starts inside a paragraph stays as it is too: its break
1014/// joins that paragraph to the next.
1015fn detach_breaks(segments: Vec<Segment>) -> Vec<Segment> {
1016    fn same(out: &mut Vec<Segment>, text: &str) {
1017        match out.last_mut() {
1018            Some(Segment::Same(same)) => same.push_str(text),
1019            _ => out.push(Segment::Same(text.to_string())),
1020        }
1021    }
1022    // Whether the next change starts its paragraph: nothing but a list,
1023    // quote or heading marker before it on its line.
1024    fn starts_paragraph(out: &[Segment]) -> bool {
1025        for segment in out.iter().rev() {
1026            match segment {
1027                Segment::Same(text) => match text.rsplit_once('\n') {
1028                    Some((_, line)) => return !visible(line),
1029                    None if visible(text) => return false,
1030                    None => {}
1031                },
1032                Segment::Edit(_) => return false,
1033                _ => {}
1034            }
1035        }
1036        true
1037    }
1038    let leads = leading_breaks(&segments);
1039    let mut out: Vec<Segment> = Vec::with_capacity(segments.len());
1040    let mut after: Option<String> = None;
1041    for (at, segment) in segments.into_iter().enumerate() {
1042        if !matches!(segment, Segment::Note(..))
1043            && let Some(text) = after.take()
1044        {
1045            same(&mut out, &text);
1046        }
1047        let Segment::Edit(mut edit) = segment else {
1048            match segment {
1049                Segment::Same(text) => same(&mut out, &text),
1050                other => out.push(other),
1051            }
1052            continue;
1053        };
1054        let side = match (edit.old.is_empty(), edit.new.is_empty()) {
1055            (false, true) => Side::Old,
1056            (true, false) => Side::New,
1057            _ => {
1058                out.push(Segment::Edit(edit));
1059                continue;
1060            }
1061        };
1062        let (plain, marked) = match side {
1063            Side::Old => (&mut edit.old, &mut edit.old_marked),
1064            Side::New => (&mut edit.new, &mut edit.new_marked),
1065        };
1066        let trailing = plain.len() - plain.trim_end_matches('\n').len();
1067        let leading = plain.len() - plain.trim_start_matches('\n').len();
1068        if leads.contains(&at) {
1069            same(&mut out, plain);
1070        } else if plain.trim().is_empty() {
1071            out.push(Segment::Edit(edit));
1072        } else if trailing >= 2
1073            && marked.ends_with(&plain[plain.len() - trailing..])
1074            && starts_paragraph(&out)
1075        {
1076            let text = plain.split_off(plain.len() - trailing);
1077            marked.truncate(marked.len() - trailing);
1078            out.push(Segment::Edit(edit));
1079            after = Some(text);
1080        } else if leading >= 2 && marked.starts_with(&plain[..leading]) {
1081            let text: String = plain.drain(..leading).collect();
1082            marked.drain(..leading);
1083            same(&mut out, &text);
1084            out.push(Segment::Edit(edit));
1085        } else {
1086            out.push(Segment::Edit(edit));
1087        }
1088    }
1089    if let Some(text) = after {
1090        same(&mut out, &text);
1091    }
1092    out
1093}
1094
1095/// The changes [`detach_breaks`] moves out as a paragraph's leading
1096/// break, by position: a change that is only a break, followed (comments
1097/// between) by the same side's changes of a paragraph's whole text, which
1098/// ends the story or a break follows. Word often splits that text into
1099/// several changes, and a line break in it is the view's hard break (`\`
1100/// before the newline). Text after the paragraph's changes, a paragraph
1101/// break in them, or another author's mark means the break joins
1102/// paragraphs (accepting it alone joins them), and it stays a change.
1103fn leading_breaks(segments: &[Segment]) -> HashSet<usize> {
1104    // The side a one-sided change makes, its text, and who made it.
1105    fn one_side(segment: &Segment) -> Option<(Side, &str, Option<&str>)> {
1106        let Segment::Edit(edit) = segment else {
1107            return None;
1108        };
1109        let author = edit.by.as_ref().map(|(author, _)| author.as_str());
1110        match (edit.old.is_empty(), edit.new.is_empty()) {
1111            (false, true) => Some((Side::Old, edit.old.as_str(), author)),
1112            (true, false) => Some((Side::New, edit.new.as_str(), author)),
1113            _ => None,
1114        }
1115    }
1116    // Text within one paragraph: every newline is a hard break.
1117    fn in_paragraph(text: &str) -> bool {
1118        text.match_indices('\n')
1119            .all(|(at, _)| text[..at].ends_with('\\'))
1120    }
1121    // The first segment from `from` on that is no comment.
1122    let next =
1123        |from: usize| (from..segments.len()).find(|&i| !matches!(segments[i], Segment::Note(..)));
1124    let mut out = HashSet::new();
1125    for (at, segment) in segments.iter().enumerate() {
1126        let Some((side, plain, author)) = one_side(segment) else {
1127            continue;
1128        };
1129        if !plain.trim().is_empty() || !plain.contains("\n\n") {
1130            continue;
1131        }
1132        let mut cursor = next(at + 1);
1133        let mut text = false;
1134        while let Some(piece) = cursor
1135            && let Some((piece_side, piece_text, piece_author)) = one_side(&segments[piece])
1136            && piece_side == side
1137            && piece_author == author
1138            && in_paragraph(piece_text)
1139        {
1140            text |= !piece_text.trim().is_empty();
1141            cursor = next(piece + 1);
1142        }
1143        if !text {
1144            continue;
1145        }
1146        let ends = match cursor.map(|i| &segments[i]) {
1147            None => true,
1148            Some(Segment::Same(after)) => after.starts_with('\n'),
1149            Some(after) => {
1150                one_side(after).is_some_and(|(s, t, _)| s == side && t.starts_with("\n\n"))
1151            }
1152        };
1153        if ends {
1154            out.insert(at);
1155        }
1156    }
1157    out
1158}
1159
1160/// A paragraph (or table row) of segments, with the line breaks before it.
1161struct Block {
1162    separator: String,
1163    /// The block before this one is in that version, so the separator is
1164    /// too.
1165    old_before_visible: bool,
1166    new_before_visible: bool,
1167    segments: Vec<Segment>,
1168}
1169
1170impl Block {
1171    fn text(&self, side: Side) -> String {
1172        let mut out = String::new();
1173        for segment in &self.segments {
1174            match segment {
1175                Segment::Same(text) => out.push_str(text),
1176                Segment::Edit(edit) => out.push_str(match side {
1177                    Side::Old => &edit.old,
1178                    Side::New => &edit.new,
1179                }),
1180                _ => {}
1181            }
1182        }
1183        out
1184    }
1185
1186    fn marked(&self, known: Option<&HashSet<String>>) -> bool {
1187        self.segments.iter().any(|s| match (s, known) {
1188            (Segment::Same(_), _) => false,
1189            (Segment::Edit(_), _) | (_, None) => true,
1190            (Segment::Note(note, _), Some(known)) => !known.contains(note),
1191            (_, Some(_)) => false,
1192        })
1193    }
1194}
1195
1196/// The segments split into blocks at the line breaks between paragraphs,
1197/// outside changes: a change across a paragraph break keeps both
1198/// paragraphs in one block.
1199fn blocks(segments: Vec<Segment>) -> Vec<Block> {
1200    let mut out: Vec<Block> = Vec::new();
1201    let mut current: Vec<Segment> = Vec::new();
1202    let mut separator = String::new();
1203    // The new version's text of the line being read.
1204    let mut line = String::new();
1205    let mut visible = (true, true);
1206    let mut close = |current: &mut Vec<Segment>, separator: &mut String, out: &mut Vec<Block>| {
1207        let block = Block {
1208            separator: std::mem::take(separator),
1209            old_before_visible: visible.0,
1210            new_before_visible: visible.1,
1211            segments: std::mem::take(current),
1212        };
1213        visible = (
1214            self::visible(&block.text(Side::Old)),
1215            self::visible(&block.text(Side::New)),
1216        );
1217        out.push(block);
1218    };
1219    for segment in segments {
1220        let Segment::Same(text) = segment else {
1221            if let Segment::Edit(edit) = &segment {
1222                match edit.new.rfind('\n') {
1223                    Some(at) => line = edit.new[at + 1..].to_string(),
1224                    None => line.push_str(&edit.new),
1225                }
1226            }
1227            current.push(segment);
1228            continue;
1229        };
1230        let mut rest = text.as_str();
1231        while let Some(at) = rest.find('\n') {
1232            let before = &rest[..at];
1233            if !before.is_empty() {
1234                push_same(&mut current, before);
1235            }
1236            line.push_str(before);
1237            let after = &rest[at + 1..];
1238            let next = after.split('\n').next().unwrap_or("");
1239            let boundary = next.trim().is_empty() || !open_paragraph(&line) || !continues(next);
1240            if boundary {
1241                if current.is_empty() {
1242                    separator.push('\n');
1243                } else {
1244                    close(&mut current, &mut separator, &mut out);
1245                    separator.push('\n');
1246                }
1247            } else if current.is_empty() {
1248                separator.push('\n');
1249            } else {
1250                push_same(&mut current, "\n");
1251            }
1252            line.clear();
1253            rest = after;
1254        }
1255        if !rest.is_empty() {
1256            push_same(&mut current, rest);
1257            line.push_str(rest);
1258        }
1259    }
1260    if !current.is_empty() {
1261        close(&mut current, &mut separator, &mut out);
1262    }
1263    out
1264}
1265
1266/// Whether a block has text in a version: more than its list, quote or
1267/// heading marker.
1268fn visible(text: &str) -> bool {
1269    let text = text.trim_start();
1270    if table_row(text) {
1271        return text
1272            .chars()
1273            .any(|c| !matches!(c, '|' | '-' | ':') && !c.is_whitespace());
1274    }
1275    !text[marker_len(text)..].trim().is_empty()
1276}
1277
1278fn push_same(segments: &mut Vec<Segment>, text: &str) {
1279    if let Some(Segment::Same(same)) = segments.last_mut() {
1280        same.push_str(text);
1281    } else {
1282        segments.push(Segment::Same(text.to_string()));
1283    }
1284}
1285
1286/// A comment's author, date and text: `Name (date): text`, or the owner's.
1287fn comment(text: &str, owner: &Attribution, on: Option<String>) -> Comment {
1288    let trimmed = text.trim();
1289    if let Some((Some(author), date, rest)) = named(trimmed)
1290        && let Some(body) = rest.strip_prefix(':').or(rest.is_empty().then_some(""))
1291    {
1292        return Comment {
1293            author,
1294            date: date.to_string(),
1295            text: body.trim().to_string(),
1296            on,
1297        };
1298    }
1299    Comment {
1300        author: owner.author.clone(),
1301        date: owner.date.clone(),
1302        text: trimmed.to_string(),
1303        on,
1304    }
1305}
1306
1307fn hunk(block: &Block, at: Locator, removed: bool, owner: &Attribution) -> Hunk {
1308    let mut text = String::new();
1309    let mut changes: Vec<Change> = Vec::new();
1310    let mut comments = Vec::new();
1311    // The highlighted text being read, and the last highlight's.
1312    let mut highlight: Option<String> = None;
1313    let mut highlighted: Option<String> = None;
1314    let mut previous: Option<&Segment> = None;
1315    for segment in &block.segments {
1316        match segment {
1317            Segment::Same(same) => {
1318                text.push_str(&escape(same));
1319                if let Some(h) = &mut highlight {
1320                    h.push_str(same);
1321                }
1322            }
1323            Segment::Edit(edit) => {
1324                // The note after a change names its author unless the
1325                // owner made it then.
1326                let named = |text: &mut String, by: &Option<(String, String)>| match by {
1327                    Some((author, date)) => {
1328                        if author != &owner.author || date != &owner.date {
1329                            text.push_str(&format!("{{>>{author} ({date})<<}}"));
1330                        }
1331                        (author.clone(), date.clone())
1332                    }
1333                    None => (owner.author.clone(), owner.date.clone()),
1334                };
1335                let mut sides = Vec::with_capacity(2);
1336                match &edit.new_by {
1337                    // Two authors: the deletion and the insertion are
1338                    // changes of their own, each named after itself.
1339                    Some(_) => {
1340                        text.push_str(&format!("[-{}-]", escape(&edit.old_marked)));
1341                        sides.push((edit.old.clone(), String::new(), named(&mut text, &edit.by)));
1342                        text.push_str(&format!("{{+{}+}}", escape(&edit.new_marked)));
1343                        sides.push((
1344                            String::new(),
1345                            edit.new.clone(),
1346                            named(&mut text, &edit.new_by),
1347                        ));
1348                    }
1349                    None => {
1350                        if !edit.old_marked.is_empty() {
1351                            text.push_str(&format!("[-{}-]", escape(&edit.old_marked)));
1352                        }
1353                        if !edit.new_marked.is_empty() {
1354                            text.push_str(&format!("{{+{}+}}", escape(&edit.new_marked)));
1355                        }
1356                        sides.push((
1357                            edit.old.clone(),
1358                            edit.new.clone(),
1359                            named(&mut text, &edit.by),
1360                        ));
1361                    }
1362                }
1363                if let Some(h) = &mut highlight {
1364                    h.push_str(&edit.new);
1365                }
1366                changes.extend(sides.into_iter().map(|(old, new, (author, date))| Change {
1367                    old,
1368                    new,
1369                    author,
1370                    date,
1371                    comment: None,
1372                }));
1373            }
1374            Segment::HighlightStart => {
1375                text.push_str("{==");
1376                highlight = Some(String::new());
1377            }
1378            Segment::HighlightEnd => {
1379                text.push_str("==}");
1380                highlighted = highlight.take();
1381            }
1382            Segment::Note(note, _) => {
1383                let on = match previous {
1384                    Some(Segment::HighlightEnd) => highlighted.take(),
1385                    _ => None,
1386                };
1387                let comment = comment(note, owner, on);
1388                text.push_str(&format!(
1389                    "{{>>{} ({}): {}<<}}",
1390                    comment.author, comment.date, comment.text
1391                ));
1392                match (previous, changes.last_mut()) {
1393                    (Some(Segment::Edit(edit)), Some(change))
1394                        if change.comment.is_none()
1395                            && edit
1396                                .new_by
1397                                .as_ref()
1398                                .or(edit.by.as_ref())
1399                                .is_none_or(|(a, d)| a == &owner.author && d == &owner.date) =>
1400                    {
1401                        change.comment = Some(comment);
1402                    }
1403                    _ => comments.push(comment),
1404                }
1405            }
1406        }
1407        previous = Some(segment);
1408    }
1409    Hunk {
1410        at,
1411        removed,
1412        text,
1413        changes,
1414        comments,
1415    }
1416}
1417
1418/// The patch's own delimiters in text, escaped so they stay text.
1419fn escape(text: &str) -> String {
1420    let mut out = String::with_capacity(text.len());
1421    let mut backslashes = 0;
1422    let mut chars = text.chars().peekable();
1423    while let Some(c) = chars.next() {
1424        let next = chars.peek().copied();
1425        match (c, next) {
1426            ('[', Some('-')) | ('{', Some('+')) if backslashes % 2 == 0 => out.push('\\'),
1427            _ => {}
1428        }
1429        out.push(c);
1430        match (c, next) {
1431            ('-', Some(']')) | ('+', Some('}')) => out.push('\\'),
1432            _ => {}
1433        }
1434        backslashes = if c == '\\' { backslashes + 1 } else { 0 };
1435    }
1436    out
1437}
1438
1439/// `text` with each line broken at spaces to fit `columns`, where Markdown
1440/// reads the break as a space.
1441fn wrap(text: &str, columns: usize) -> String {
1442    let mut out: Vec<String> = Vec::new();
1443    let mut fenced = false;
1444    for line in text.split('\n') {
1445        let trimmed = line.trim_start();
1446        let fence = trimmed.starts_with("```") || trimmed.starts_with("~~~");
1447        let keep = columns == 0
1448            || fenced
1449            || fence
1450            || trimmed.starts_with('#')
1451            || table_row(line)
1452            || line.chars().count() <= columns;
1453        if fence {
1454            fenced = !fenced;
1455        }
1456        if keep {
1457            out.push(line.to_string());
1458        } else {
1459            out.extend(break_line(line, columns).into_iter().map(str::to_string));
1460        }
1461    }
1462    out.join("\n")
1463}
1464
1465fn break_line(line: &str, columns: usize) -> Vec<&str> {
1466    let protected = protected(line);
1467    let breaks: Vec<usize> = line
1468        .char_indices()
1469        .filter(|&(at, c)| c == ' ' && can_break(line, at, &protected))
1470        .map(|(at, _)| at)
1471        .collect();
1472    let mut out = Vec::new();
1473    let mut start = 0;
1474    loop {
1475        let width = |end: usize| line[start..end].chars().count();
1476        if width(line.len()) <= columns {
1477            break;
1478        }
1479        let candidates = breaks.iter().copied().filter(|&b| b > start);
1480        let fitting = candidates
1481            .clone()
1482            .take_while(|&b| width(b) <= columns)
1483            .last();
1484        let Some(at) = fitting.or_else(|| candidates.clone().next()) else {
1485            break;
1486        };
1487        out.push(&line[start..at]);
1488        start = at + 1;
1489    }
1490    out.push(&line[start..]);
1491    out
1492}
1493
1494/// Byte ranges no break may fall in: code spans, link targets, autolinks.
1495fn protected(line: &str) -> Vec<(usize, usize)> {
1496    let bytes = line.as_bytes();
1497    let mut out = Vec::new();
1498    let mut at = 0;
1499    while at < bytes.len() {
1500        match bytes[at] {
1501            b'\\' => at += 2,
1502            b'`' => {
1503                let run = bytes[at..].iter().take_while(|b| **b == b'`').count();
1504                let fence = &line[at..at + run];
1505                let mut end = at + run;
1506                let mut closed = None;
1507                while let Some(found) = line[end..].find(fence) {
1508                    let start = end + found;
1509                    let length = bytes[start..].iter().take_while(|b| **b == b'`').count();
1510                    if length == run {
1511                        closed = Some(start + run);
1512                        break;
1513                    }
1514                    end = start + length;
1515                }
1516                match closed {
1517                    Some(close) => {
1518                        out.push((at, close));
1519                        at = close;
1520                    }
1521                    None => at += run,
1522                }
1523            }
1524            b']' if bytes.get(at + 1) == Some(&b'(') => {
1525                let mut depth = 0;
1526                let mut end = at + 1;
1527                while end < bytes.len() {
1528                    match bytes[end] {
1529                        b'(' => depth += 1,
1530                        b')' => {
1531                            depth -= 1;
1532                            if depth == 0 {
1533                                break;
1534                            }
1535                        }
1536                        b'\\' => end += 1,
1537                        _ => {}
1538                    }
1539                    end += 1;
1540                }
1541                out.push((at, end.min(bytes.len())));
1542                at = end + 1;
1543            }
1544            b'<' if line[at + 1..].starts_with("http") || line[at + 1..].starts_with("mailto:") => {
1545                let end = line[at..].find('>').map_or(bytes.len(), |e| at + e + 1);
1546                out.push((at, end));
1547                at = end;
1548            }
1549            _ => at += 1,
1550        }
1551    }
1552    out
1553}
1554
1555/// The markers that open and close a deletion, insertion, highlight and
1556/// comment.
1557const OPENERS: [&str; 4] = ["[-", "{+", "{==", "{>>"];
1558const CLOSERS: [&str; 4] = ["-]", "+}", "==}", "<<}"];
1559
1560/// Whether the space at byte `at` may become a line break.
1561fn can_break(line: &str, at: usize, protected: &[(usize, usize)]) -> bool {
1562    if protected.iter().any(|&(start, end)| start < at && at < end) {
1563        return false;
1564    }
1565    let before = &line[..at];
1566    let after = &line[at + 1..];
1567    if before.is_empty()
1568        || before.ends_with([' ', '\\'])
1569        || after.is_empty()
1570        || after.starts_with(' ')
1571    {
1572        return false;
1573    }
1574    // A change marker stays on the line of the text it marks: no line ends
1575    // with an opening marker or starts with a closing one (`{+paragraph` /
1576    // `+}style` read as two changes).
1577    if OPENERS.iter().any(|m| before.ends_with(m)) || CLOSERS.iter().any(|m| after.starts_with(m)) {
1578        return false;
1579    }
1580    !starts_block(after)
1581}
1582
1583/// Whether a line starting with `text` would start a block of its own.
1584fn starts_block(text: &str) -> bool {
1585    let word = text.split(' ').next().unwrap_or("");
1586    marker_len(text) > 0
1587        || text.starts_with(['|', '>', '#', '<'])
1588        || text.starts_with("```")
1589        || text.starts_with("~~~")
1590        || (!word.is_empty() && word.chars().all(|c| c == '=' || c == '-'))
1591        || (word.len() > 1 && word.chars().all(|c| c == '*' || c == '_'))
1592        || (word.ends_with(['.', ')'])
1593            && word[..word.len() - 1].bytes().all(|b| b.is_ascii_digit())
1594            && word.len() > 1)
1595}
1596
1597#[cfg(test)]
1598#[cfg_attr(all(coverage_nightly, test), coverage(off))]
1599mod tests {
1600    use super::*;
1601
1602    #[test]
1603    fn a_wrap_never_strands_a_change_marker() {
1604        // The heading pair wrapped as `{+paragraph` / `+}style`: the break
1605        // was the inserted space itself.
1606        let line = "**This document [-shows-]{+demonstrates+} Heading 1 {+paragraph +}style[- with extra bold emphasis-].** {==see==}{>>note <<} end";
1607        for columns in [20, 40, 56, 60, 72] {
1608            let wrapped = wrap(line, columns);
1609            assert_eq!(wrapped.replace('\n', " "), line, "{columns}");
1610            for row in wrapped.lines() {
1611                for close in ["+}", "-]", "==}", "<<}"] {
1612                    assert!(
1613                        !row.starts_with(close),
1614                        "{columns}: {row:?} starts with {close}"
1615                    );
1616                }
1617                for open in ["{+", "[-", "{==", "{>>"] {
1618                    assert!(!row.ends_with(open), "{columns}: {row:?} ends with {open}");
1619                }
1620            }
1621        }
1622    }
1623
1624    #[test]
1625    fn escapes_only_unescaped_delimiters() {
1626        assert_eq!(escape("a [-b-] {+c+}"), "a \\[-b-\\] \\{+c+\\}");
1627        assert_eq!(escape("\\[-b"), "\\[-b");
1628        assert_eq!(escape("x-y [z]"), "x-y [z]");
1629    }
1630
1631    #[test]
1632    fn protects_code_links_and_autolinks() {
1633        let line = "a `b c` [d](e f) <http://g h>";
1634        let ranges = protected(line);
1635        assert_eq!(ranges.len(), 3, "{ranges:?}");
1636        assert!(!can_break(line, line.find(" c`").unwrap(), &ranges));
1637        assert!(!can_break(line, line.find(" f)").unwrap(), &ranges));
1638        assert!(can_break(line, 1, &ranges));
1639    }
1640
1641    #[test]
1642    fn a_numbered_note_after_a_change_names_its_author_never_a_comment() {
1643        let owner = Attribution {
1644            author: "Owner".to_string(),
1645            date: "2026-01-01T00:00:00Z".to_string(),
1646        };
1647        let by = |critic: &str| {
1648            attribute(segments(critic), &HashMap::new(), &owner)
1649                .into_iter()
1650                .map(|segment| match segment {
1651                    Segment::Edit(edit) => format!("edit {:?}", edit.by),
1652                    Segment::Note(note, _) => format!("note {note}"),
1653                    _ => String::new(),
1654                })
1655                .filter(|s| !s.is_empty())
1656                .collect::<Vec<_>>()
1657        };
1658        let ana = Some(("Ana Lima".to_string(), "2026-09-30T14:05:00Z".to_string()));
1659        assert_eq!(
1660            by("a {++b++}{r3 Ana Lima (2026-09-30T14:05:00Z)} c"),
1661            [format!("edit {ana:?}")]
1662        );
1663        assert_eq!(
1664            by("a {++b++}{footnotes.r3+4 Ana Lima (2026-09-30T14:05:00Z)}"),
1665            [format!("edit {ana:?}")]
1666        );
1667        // The old note without a number still names the author.
1668        assert_eq!(
1669            by("a {++b++}{noid Ana Lima (2026-09-30T14:05:00Z)}"),
1670            [format!("edit {ana:?}")]
1671        );
1672        // A number alone names the change and no one: the owner made it.
1673        assert_eq!(by("a {++b++}{r3}"), ["edit None"]);
1674        // A comment is still a comment.
1675        assert_eq!(
1676            by("a {++b++}{>>Ana Lima (2026-09-30T14:05:00Z): why<<}"),
1677            ["edit None", "note Ana Lima (2026-09-30T14:05:00Z): why"]
1678        );
1679    }
1680
1681    #[test]
1682    fn plain_text_drops_markers_targets_note_references_and_tags() {
1683        assert_eq!(plain("- a<u>b</u>c [d](e)[^1] x < y"), "abc [d] x < y");
1684    }
1685
1686    #[test]
1687    fn no_line_starts_a_block() {
1688        for text in [
1689            "- x", "* x", "+ x", "1. x", "12) x", "# x", "> x", "| x", "=== x", "--- x", "```",
1690            "<div>",
1691        ] {
1692            assert!(starts_block(text), "{text}");
1693        }
1694        for text in ["x", "1.5 x", "-5 x", "word"] {
1695            assert!(!starts_block(text), "{text}");
1696        }
1697    }
1698}
1699
1700#[cfg(test)]
1701#[cfg_attr(all(coverage_nightly, test), coverage(off))]
1702mod literal_wrapping_boundary_tests {
1703    use super::*;
1704
1705    #[test]
1706    fn protected_source_ranges_keep_exact_code_target_and_autolink_owners() {
1707        for (source, owned) in [
1708            ("before ``one ` two`` after", "``one ` two``"),
1709            ("before `one `` two` after", "`one `` two`"),
1710            (
1711                "before [label](outer(inner) tail) after",
1712                "](outer(inner) tail",
1713            ),
1714            (r"before [label](escaped\) tail) after", r"](escaped\) tail"),
1715            ("before [label](unterminated tail", "](unterminated tail"),
1716            ("before <mailto:one two> after", "<mailto:one two>"),
1717            ("before <https://one two", "<https://one two"),
1718        ] {
1719            let ranges = protected(source);
1720            assert_eq!(ranges.len(), 1, "{source}");
1721            assert_eq!(&source[ranges[0].0..ranges[0].1], owned, "{source}");
1722            for (at, c) in source
1723                .char_indices()
1724                .filter(|(at, c)| *c == ' ' && ranges[0].0 < *at && *at < ranges[0].1)
1725            {
1726                assert_eq!(c, ' ');
1727                assert!(!can_break(source, at, &ranges));
1728            }
1729            let wrapped = wrap(source, 8);
1730            assert_eq!(wrapped.replace('\n', " "), source);
1731            assert!(wrapped.contains(owned));
1732        }
1733        for source in [
1734            "before `unclosed tail",
1735            r"before \`literal tail",
1736            "before <ordinary tail>",
1737            r"before [label]\(literal tail)",
1738        ] {
1739            assert!(protected(source).is_empty(), "{source}");
1740            assert_eq!(wrap(source, 8).replace('\n', " "), source);
1741        }
1742    }
1743
1744    #[test]
1745    fn exact_markdown_break_guards_preserve_literal_whitespace_and_block_markers() {
1746        for source in [" leading", "trailing ", "double  space", r"escaped\ space"] {
1747            for (at, _) in source.char_indices().filter(|(_, c)| *c == ' ') {
1748                assert!(!can_break(source, at, &[]), "{source:?} at {at}");
1749            }
1750        }
1751        for marker in ["[-", "{+", "{==", "{>>"] {
1752            let source = format!("{marker} text");
1753            assert!(!can_break(&source, marker.len(), &[]));
1754        }
1755        for marker in ["-]", "+}", "==}", "<<}"] {
1756            let source = format!("text {marker}");
1757            assert!(!can_break(&source, 4, &[]));
1758        }
1759        for (suffix, starts) in [
1760            ("*** text", true),
1761            ("__ text", true),
1762            ("~~~", true),
1763            ("12) text", true),
1764            ("1x. text", false),
1765            (". text", false),
1766            ("a*b text", false),
1767            ("=x text", false),
1768            ("", false),
1769        ] {
1770            assert_eq!(starts_block(suffix), starts, "{suffix}");
1771            let source = format!("owned {suffix}");
1772            assert_eq!(
1773                can_break(&source, 5, &[]),
1774                !starts && !suffix.is_empty(),
1775                "{suffix}"
1776            );
1777        }
1778        assert_eq!(wrap("αβ γδ εζ", 5), "αβ γδ\nεζ");
1779        assert_eq!(wrap("unbreakable", 1), "unbreakable");
1780        assert_eq!(wrap("a b c", 0), "a b c");
1781        let fenced = "~~~rust\nowned very long source\n~~~\na b c";
1782        assert_eq!(
1783            wrap(fenced, 3),
1784            "~~~rust\nowned very long source\n~~~\na b\nc"
1785        );
1786    }
1787}
1788
1789#[cfg(test)]
1790#[cfg_attr(all(coverage_nightly, test), coverage(off))]
1791mod review_tests {
1792    use super::*;
1793
1794    #[test]
1795    fn review_paragraph_tag_keeps_an_incomplete_trailing_separator() {
1796        let text = segments("A¶{r1 Alice}\n")
1797            .into_iter()
1798            .filter_map(|segment| match segment {
1799                Segment::Same(text) => Some(text),
1800                _ => None,
1801            })
1802            .collect::<String>();
1803        assert_eq!(text, "A\n");
1804    }
1805}
1806
1807#[cfg(test)]
1808#[cfg_attr(all(coverage_nightly, test), coverage(off))]
1809mod attribution_branch_tests {
1810    use super::super::view_notes::Author;
1811    use super::*;
1812
1813    const D1: &str = "2026-01-02T03:04:05Z";
1814    const D2: &str = "2026-02-03T04:05:06Z";
1815
1816    fn owner() -> Attribution {
1817        Attribution {
1818            author: "Owner".to_string(),
1819            date: "2026-01-01T00:00:00Z".to_string(),
1820        }
1821    }
1822
1823    fn change(old: &str, new: &str) -> Segment {
1824        let mut edit = Edit::default();
1825        if !old.is_empty() {
1826            edit.push(Side::Old, old, true);
1827        }
1828        if !new.is_empty() {
1829            edit.push(Side::New, new, true);
1830        }
1831        Segment::Edit(edit)
1832    }
1833
1834    fn tag(text: &str) -> Segment {
1835        Segment::Note(text.to_string(), true)
1836    }
1837
1838    fn who(author: &str, date: &str) -> Option<(String, String)> {
1839        Some((author.to_string(), date.to_string()))
1840    }
1841
1842    type By = (Option<(String, String)>, Option<(String, String)>);
1843
1844    /// Each edit's (deletion-or-only, insertion) attribution, and every
1845    /// note that stayed a note.
1846    fn run(segments: Vec<Segment>, authors: &HashMap<String, Author>) -> (Vec<By>, Vec<String>) {
1847        let mut edits = Vec::new();
1848        let mut notes = Vec::new();
1849        for segment in attribute(segments, authors, &owner()) {
1850            match segment {
1851                Segment::Edit(edit) => edits.push((edit.by, edit.new_by)),
1852                Segment::Note(text, _) => notes.push(text),
1853                _ => {}
1854            }
1855        }
1856        (edits, notes)
1857    }
1858
1859    fn authors() -> HashMap<String, Author> {
1860        HashMap::from([
1861            (
1862                "AL".to_string(),
1863                Author {
1864                    name: "Ana Lima".to_string(),
1865                    date: None,
1866                    latest: None,
1867                    range: Some(("2026-03-02".to_string(), "2026-03-04".to_string())),
1868                },
1869            ),
1870            (
1871                "BO".to_string(),
1872                Author {
1873                    name: "Ben Ode".to_string(),
1874                    date: Some(D1.to_string()),
1875                    latest: None,
1876                    range: None,
1877                },
1878            ),
1879            (
1880                "LT".to_string(),
1881                Author {
1882                    name: "Lia Tam".to_string(),
1883                    date: None,
1884                    latest: Some(D2.to_string()),
1885                    range: Some(("2026-03-02".to_string(), "2026-03-04".to_string())),
1886                },
1887            ),
1888            (
1889                "ND".to_string(),
1890                Author {
1891                    name: "No Date".to_string(),
1892                    date: None,
1893                    latest: None,
1894                    range: None,
1895                },
1896            ),
1897        ])
1898    }
1899
1900    #[test]
1901    fn two_plain_parts_name_each_side_of_a_substitution_only() {
1902        let none = HashMap::new();
1903        let (edits, notes) = run(
1904            vec![
1905                change("a", "b"),
1906                tag(&format!("r1 Ana Lima ({D1}); r2 ({D2})")),
1907            ],
1908            &none,
1909        );
1910        assert_eq!(edits, [(who("Ana Lima", D1), who("", D2))]);
1911        assert!(notes.is_empty());
1912        // Parts that name no one and carry no date leave both sides open.
1913        let (edits, _) = run(vec![change("a", "b"), tag("r1; r2")], &none);
1914        assert_eq!(edits, [(None, None)]);
1915        // Two parts on a one-sided change are no substitution: the first
1916        // plain revision path does not apply, and the note names no one.
1917        for one_sided in [change("", "b"), change("a", "")] {
1918            let (edits, notes) = run(
1919                vec![
1920                    one_sided,
1921                    tag(&format!("r1 Ana Lima ({D1}); r2 Ben ({D2})")),
1922                ],
1923                &none,
1924            );
1925            assert_eq!(edits, [(None, None)]);
1926            assert_eq!(notes, [format!("r1 Ana Lima ({D1}); r2 Ben ({D2})")]);
1927        }
1928    }
1929
1930    #[test]
1931    fn agent_tags_resolve_through_the_authors_table() {
1932        let table = authors();
1933        // Two tags on a substitution: deletion, then insertion; the ranged
1934        // author's insertion takes the last day of the range.
1935        let (edits, _) = run(vec![change("a", "b"), tag("r1 @BO; r2 @AL")], &table);
1936        assert_eq!(
1937            edits,
1938            [(who("Ben Ode", D1), who("Ana Lima", "2026-03-04T23:59:59Z"))]
1939        );
1940        // One ranged tag on a substitution: the insertion keeps the first
1941        // day and the deletion takes the last.
1942        let (edits, _) = run(vec![change("a", "b"), tag("r1 @AL")], &table);
1943        assert_eq!(
1944            edits,
1945            [(
1946                who("Ana Lima", "2026-03-04T23:59:59Z"),
1947                who("Ana Lima", "2026-03-02T00:00:00Z")
1948            )]
1949        );
1950        // One ranged tag on an insertion takes the last day.
1951        let (edits, _) = run(vec![change("", "b"), tag("r1 @AL")], &table);
1952        assert_eq!(edits, [(who("Ana Lima", "2026-03-04T23:59:59Z"), None)]);
1953        // A dated tag wins over the table, and is no range.
1954        let (edits, _) = run(vec![change("", "b"), tag(&format!("r1 @AL {D2}"))], &table);
1955        assert_eq!(edits, [(who("Ana Lima", D2), None)]);
1956        // The latest date of a row with a range wins over the range.
1957        let (edits, _) = run(vec![change("", "b"), tag("r1 @LT")], &table);
1958        assert_eq!(edits, [(who("Lia Tam", D2), None)]);
1959        // A row with no date leaves the change undated; an unknown handle
1960        // takes the owner; the unnamed handle names no one.
1961        let (edits, _) = run(
1962            vec![
1963                change("", "b"),
1964                tag("r1 @ND"),
1965                change("", "c"),
1966                tag("r2 @ZZ"),
1967                change("", "d"),
1968                tag("r3 @??"),
1969            ],
1970            &table,
1971        );
1972        assert_eq!(
1973            edits,
1974            [
1975                (who("No Date", ""), None),
1976                (who("Owner", "2026-01-01T00:00:00Z"), None),
1977                (who("", ""), None),
1978            ]
1979        );
1980        // Two tags on a one-sided change: the first names it.
1981        let (edits, _) = run(vec![change("", "b"), tag("r1 @BO; r2 @ND")], &table);
1982        assert_eq!(edits, [(who("Ben Ode", D1), None)]);
1983        // A nested tag names the change by its own (first) tag.
1984        let (edits, _) = run(vec![change("a", ""), tag("r3 @BO re r1 @ND")], &table);
1985        assert_eq!(edits, [(who("Ben Ode", D1), None)]);
1986    }
1987
1988    #[test]
1989    fn later_tags_fill_the_open_side_or_stay_notes() {
1990        let table = authors();
1991        // A second single tag on a substitution names the insertion; a third
1992        // has no side left and stays a note.
1993        let (edits, notes) = run(
1994            vec![
1995                change("a", "b"),
1996                tag("r1 @BO"),
1997                tag("r2 @AL"),
1998                tag("r3 @ND"),
1999            ],
2000            &table,
2001        );
2002        assert_eq!(
2003            edits,
2004            [(who("Ben Ode", D1), who("Ana Lima", "2026-03-04T23:59:59Z"))]
2005        );
2006        assert_eq!(notes, ["r3 @ND"]);
2007        // A number alone names no one; the next tag on the one-sided
2008        // change then names it.
2009        let (edits, _) = run(vec![change("", "b"), tag("r3"), tag("r4 @BO")], &table);
2010        assert_eq!(edits, [(who("Ben Ode", D1), None)]);
2011        // A named one-sided change keeps its author against a later tag.
2012        let (edits, notes) = run(vec![change("", "b"), tag("r1 @BO"), tag("r2 @ND")], &table);
2013        assert_eq!(edits, [(who("Ben Ode", D1), None)]);
2014        assert_eq!(notes, ["r2 @ND"]);
2015    }
2016
2017    #[test]
2018    fn plain_and_named_notes_fill_sides_in_order() {
2019        let none = HashMap::new();
2020        // Plain revisions: the first names the deletion, the second the
2021        // insertion; a nameless third stays a note.
2022        let (edits, notes) = run(
2023            vec![
2024                change("a", "b"),
2025                tag(&format!("r1 Ana Lima ({D1})")),
2026                tag(&format!("r2 Ben Ode ({D2})")),
2027                tag("r3"),
2028            ],
2029            &none,
2030        );
2031        assert_eq!(edits, [(who("Ana Lima", D1), who("Ben Ode", D2))]);
2032        assert_eq!(notes, ["r3"]);
2033        // A bare `Name (date)` note names a change too.
2034        let (edits, _) = run(
2035            vec![change("", "b"), tag(&format!("Ana Lima ({D1})"))],
2036            &none,
2037        );
2038        assert_eq!(edits, [(who("Ana Lima", D1), None)]);
2039        // A dated note with no name, or a comment after a name, names no
2040        // one and stays.
2041        let (edits, notes) = run(
2042            vec![
2043                change("", "b"),
2044                tag(&format!("({D1})")),
2045                tag(&format!("Ana Lima ({D1}): why")),
2046            ],
2047            &none,
2048        );
2049        assert_eq!(edits, [(None, None)]);
2050        assert_eq!(notes.len(), 2);
2051        // A nameless number leaves the substitution's insertion open to the
2052        // next named note, never to another nameless one.
2053        let (edits, notes) = run(
2054            vec![
2055                change("a", "b"),
2056                tag(&format!("r1 Ana Lima ({D1})")),
2057                tag("r2"),
2058            ],
2059            &none,
2060        );
2061        assert_eq!(edits, [(who("Ana Lima", D1), None)]);
2062        assert_eq!(notes, ["r2"]);
2063        // On a one-sided change named by nobody, a later plain note names it.
2064        let (edits, _) = run(
2065            vec![
2066                change("a", ""),
2067                tag("r2"),
2068                tag(&format!("r3 Ben Ode ({D2})")),
2069            ],
2070            &none,
2071        );
2072        assert_eq!(edits, [(who("Ben Ode", D2), None)]);
2073    }
2074}
2075
2076#[cfg(test)]
2077#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2078mod segment_branch_tests {
2079    use super::*;
2080
2081    fn show(segments: &[Segment]) -> Vec<String> {
2082        segments
2083            .iter()
2084            .map(|s| match s {
2085                Segment::Same(t) => format!("S:{t}"),
2086                Segment::Edit(e) => {
2087                    format!("E:{}|{}|{}|{}", e.old, e.new, e.old_marked, e.new_marked)
2088                }
2089                Segment::Note(t, a) => format!("N:{t}:{a}"),
2090                Segment::HighlightStart => "H<".to_string(),
2091                Segment::HighlightEnd => "H>".to_string(),
2092            })
2093            .collect()
2094    }
2095
2096    fn insert(text: &str) -> Segment {
2097        let mut edit = Edit::default();
2098        edit.push(Side::New, text, true);
2099        Segment::Edit(edit)
2100    }
2101
2102    fn delete(text: &str) -> Segment {
2103        let mut edit = Edit::default();
2104        edit.push(Side::Old, text, true);
2105        Segment::Edit(edit)
2106    }
2107
2108    fn marked_insert(plain: &str, marked: &str) -> Segment {
2109        Segment::Edit(Edit {
2110            new: plain.to_string(),
2111            new_marked: marked.to_string(),
2112            ..Edit::default()
2113        })
2114    }
2115
2116    fn by(segment: Segment, author: &str) -> Segment {
2117        match segment {
2118            Segment::Edit(mut edit) => {
2119                edit.by = Some((author.to_string(), String::new()));
2120                Segment::Edit(edit)
2121            }
2122            other => other,
2123        }
2124    }
2125
2126    #[test]
2127    fn highlight_marks_are_text_in_plain_runs_changes_and_comments() {
2128        assert_eq!(show(&segments("a ==b== c")), ["S:a ==b== c"]);
2129        assert_eq!(
2130            show(&segments("x {++y ==z== w++} {>>see ==q==<<}")),
2131            ["S:x ", "E:|y z w||y ==z== w", "S: ", "N:see ==q==:false"]
2132        );
2133    }
2134
2135    #[test]
2136    fn a_paragraph_tag_owns_the_separator_after_it() {
2137        // Two newlines after the tag: a boundary change named by the tag.
2138        assert_eq!(
2139            show(&segments("a¶{r1 @AL}\n\nb")),
2140            ["S:a", "E:|\n\n||\n\n", "N:r1 @AL:true", "S:b"]
2141        );
2142        // CRLF separators count as one break each.
2143        assert_eq!(
2144            show(&segments("a¶{r1 @AL}\r\n\r\nb")),
2145            ["S:a", "E:|\r\n\r\n||\r\n\r\n", "N:r1 @AL:true", "S:b"]
2146        );
2147        // Text right after the tag: no separator to own.
2148        assert_eq!(show(&segments("a¶{r1 @AL}b")), ["S:ab"]);
2149        // A single break at the end stays text.
2150        assert_eq!(show(&segments("a¶{r1 @AL}\n")), ["S:a\n"]);
2151    }
2152
2153    #[test]
2154    fn detach_breaks_moves_paragraph_marks_out_of_whole_paragraph_changes() {
2155        // A whole inserted paragraph that ends the story: its break follows.
2156        assert_eq!(
2157            show(&detach_breaks(vec![insert("Para.\n\n")])),
2158            ["E:|Para.||Para.", "S:\n\n"]
2159        );
2160        // After visible text on the same line the change starts inside a
2161        // paragraph and keeps its break.
2162        assert_eq!(
2163            show(&detach_breaks(vec![
2164                Segment::Same("x".into()),
2165                insert("Para.\n\n")
2166            ])),
2167            ["S:x", "E:|Para.\n\n||Para.\n\n"]
2168        );
2169        // Markup after the break keeps the break inside.
2170        assert_eq!(
2171            show(&detach_breaks(vec![marked_insert(
2172                "Para.\n\n",
2173                "Para.\n\n=="
2174            )])),
2175            ["E:|Para.\n\n||Para.\n\n=="]
2176        );
2177        // A leading break moves out before the change.
2178        assert_eq!(
2179            show(&detach_breaks(vec![
2180                Segment::Same("a".into()),
2181                delete("\n\nGone")
2182            ])),
2183            ["S:a\n\n", "E:Gone||Gone|"]
2184        );
2185        // Unless markup leads the change.
2186        assert_eq!(
2187            show(&detach_breaks(vec![marked_insert("\n\nNew", "==\n\nNew")])),
2188            ["E:|\n\nNew||==\n\nNew"]
2189        );
2190    }
2191
2192    #[test]
2193    fn leading_breaks_need_a_whole_same_side_paragraph_after_them() {
2194        let note = || Segment::Note("r1 @AL".into(), true);
2195        // Break, then the paragraph's text ending the story.
2196        assert_eq!(
2197            leading_breaks(&[insert("\n\n"), note(), insert("Para.")]),
2198            HashSet::from([0])
2199        );
2200        // The other side's change after the break: no paragraph.
2201        assert!(leading_breaks(&[insert("\n\n"), delete("x")]).is_empty());
2202        // Another author's text: no paragraph.
2203        assert!(leading_breaks(&[insert("\n\n"), by(insert("Para."), "Bo")]).is_empty());
2204        // A soft line break inside the paragraph is fine; a plain newline
2205        // is a second paragraph.
2206        assert_eq!(
2207            leading_breaks(&[insert("\n\n"), insert("one\\\ntwo")]),
2208            HashSet::from([0])
2209        );
2210        assert!(leading_breaks(&[insert("\n\n"), insert("one\ntwo")]).is_empty());
2211        // A same-side change starting a new paragraph ends it; another
2212        // side's change does not.
2213        assert_eq!(
2214            leading_breaks(&[insert("\n\n"), insert("P"), insert("\n\nQ")]),
2215            HashSet::from([0])
2216        );
2217        assert!(leading_breaks(&[insert("\n\n"), insert("P"), delete("\n\nQ")]).is_empty());
2218        // Text after the paragraph on the same line joins paragraphs.
2219        assert!(
2220            leading_breaks(&[insert("\n\n"), insert("P"), Segment::Same(" tail".into())])
2221                .is_empty()
2222        );
2223        assert_eq!(
2224            leading_breaks(&[insert("\n\n"), insert("P"), Segment::Same("\nnext".into())]),
2225            HashSet::from([0])
2226        );
2227    }
2228
2229    #[test]
2230    fn soft_breaks_inside_a_paragraph_keep_one_block() {
2231        // A continuation line after an empty block start goes to the
2232        // separator, not the block.
2233        let out = blocks(vec![Segment::Same("\ncontinued\n\nnext".into())]);
2234        assert_eq!(out.len(), 2);
2235        assert_eq!(out[0].separator, "\n");
2236        assert_eq!(out[0].text(Side::New), "continued");
2237        assert_eq!(out[1].separator, "\n\n");
2238        assert_eq!(out[1].text(Side::Old), "next");
2239    }
2240
2241    #[test]
2242    fn comments_need_a_colon_after_the_attribution() {
2243        let owner = Attribution {
2244            author: "Owner".into(),
2245            date: "2026-01-01T00:00:00Z".into(),
2246        };
2247        let named = comment("Ana Lima (2026-02-02T00:00:00Z): why", &owner, None);
2248        assert_eq!(
2249            (named.author.as_str(), named.text.as_str()),
2250            ("Ana Lima", "why")
2251        );
2252        let bare = comment("Ana Lima (2026-02-02T00:00:00Z)", &owner, None);
2253        assert_eq!((bare.author.as_str(), bare.text.as_str()), ("Ana Lima", ""));
2254        let text_after = comment("Ana Lima (2026-02-02T00:00:00Z) why", &owner, None);
2255        assert_eq!(text_after.author, "Owner");
2256        assert_eq!(text_after.text, "Ana Lima (2026-02-02T00:00:00Z) why");
2257    }
2258
2259    #[test]
2260    fn tilde_fences_keep_long_code_lines_whole() {
2261        let long = "word ".repeat(20);
2262        let text = format!("~~~\n{long}\n~~~\n{long}");
2263        let wrapped = wrap(&text, 20);
2264        let lines: Vec<&str> = wrapped.lines().collect();
2265        assert_eq!(lines[0], "~~~");
2266        assert_eq!(lines[1], long);
2267        assert_eq!(lines[2], "~~~");
2268        assert!(lines[3..].iter().all(|l| l.chars().count() <= 20));
2269    }
2270}
2271
2272#[cfg(test)]
2273#[cfg_attr(all(coverage_nightly, test), coverage(off))]
2274mod fence_branch_tests {
2275    use super::super::view_notes::Author;
2276    use super::*;
2277
2278    #[test]
2279    fn backtick_fences_keep_their_lines_whole() {
2280        let text = "```\na code line far longer than ten columns\n```\nprose words that wrap";
2281        let wrapped = wrap(text, 10);
2282        assert_eq!(
2283            wrapped,
2284            "```\na code line far longer than ten columns\n```\nprose\nwords that\nwrap"
2285        );
2286    }
2287
2288    #[test]
2289    fn only_a_bare_range_dates_marks_by_range() {
2290        let range = Some(("2026-03-02".to_string(), "2026-03-04".to_string()));
2291        let author = |date: Option<&str>, latest: Option<&str>, range| Author {
2292            name: "A".to_string(),
2293            date: date.map(str::to_string),
2294            latest: latest.map(str::to_string),
2295            range,
2296        };
2297        assert!(ranged_only(&author(None, None, range.clone())));
2298        assert!(!ranged_only(&author(
2299            Some("2026-03-02"),
2300            None,
2301            range.clone()
2302        )));
2303        assert!(!ranged_only(&author(None, Some("2026-03-04"), range)));
2304        assert!(!ranged_only(&author(None, None, None)));
2305    }
2306}