Skip to main content

jubarte_edit/edit/
hint.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! What a refusal says when another author's revision holds the text
6//! (#1108): the revision by id, author and text, then each way around it
7//! with what that way costs, quoted in the syntax the caller wrote.
8
9use crate::namespaces::W;
10use crate::xmllinq::{Dom, NodeId};
11
12/// The request syntax a refusal quotes, so a hint never names a form the
13/// caller's parser would reject.
14#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
15pub enum PlanSyntax {
16    /// A `schema_version: 1` JSON plan (`edit --plan`, the library).
17    #[default]
18    V1,
19    /// The operation flags (`edit FILE -p p3 --anchor … --content …`).
20    Flags,
21    /// A `schema_version: 2` plan (`edit apply`).
22    V2,
23    /// The typed commands (`edit replace FILE --at p3 --find … --text …`),
24    /// which take their decisions as `--accept-change` / `--reject-change`.
25    Typed,
26}
27
28impl PlanSyntax {
29    /// Every syntax, for the tests that check each one's fragments.
30    pub const ALL: [Self; 4] = [Self::V1, Self::Flags, Self::V2, Self::Typed];
31
32    /// A partial change selection, with the whole-change retry in the
33    /// caller's flags. Plans retain their released wording (#1895).
34    pub(super) fn incomplete_change(
35        self,
36        error: &crate::changes::ChangeError,
37        verb: &str,
38    ) -> String {
39        if let (
40            Self::Flags | Self::Typed,
41            crate::changes::ChangeError::PartOfChange { named, whole, .. },
42        ) = (self, error)
43        {
44            format!(
45                "{named} is part of {whole}; name the whole change: {}",
46                settle_revision(self, verb, whole, "")
47            )
48        } else {
49            format!("resolve_revisions: {error}")
50        }
51    }
52
53    /// Selection errors quote plan fields only for a plan caller.
54    pub(super) fn selection_message(self, message: impl std::fmt::Display) -> String {
55        match self {
56            Self::V1 | Self::V2 => format!("resolve_revisions: {message}"),
57            Self::Flags | Self::Typed => message.to_string(),
58        }
59    }
60
61    /// Quote the occurrence selector in the caller's grammar. Plans retain
62    /// #1013's released wording; one-shot flags also show every candidate.
63    pub(super) fn ambiguous_anchor(
64        self,
65        text: &str,
66        anchor: &str,
67        hits: &[(usize, usize)],
68    ) -> String {
69        let shown = super::anchor::shown(anchor);
70        let n = hits.len();
71        let selector = match self {
72            Self::Flags | Self::Typed => format!("set --occurrence 1..={n}"),
73            Self::V1 | Self::V2 => format!("set \"occurrence\" to 1..={n}"),
74        };
75        let mut message = format!("{shown} occurs {n} times in the paragraph; {selector}");
76        if self == Self::Flags {
77            for (i, &(start, end)) in hits.iter().enumerate() {
78                let before = if text[..start].chars().nth_back(20).is_some() {
79                    "…"
80                } else {
81                    ""
82                };
83                let after = if text[end..].chars().nth(20).is_some() {
84                    "…"
85                } else {
86                    ""
87                };
88                let window = super::context(text, start, end, &text[start..end]);
89                message.push_str(&format!(
90                    "\n  {}: {}",
91                    i + 1,
92                    super::anchor::shown(&format!("{before}{window}{after}"))
93                ));
94            }
95            message.push_str(
96                "\nlengthen --anchor to the words around the one you mean, or pass --occurrence",
97            );
98        }
99        message
100    }
101
102    /// The same choice as a refusal's data records it.
103    pub(super) const fn revision(self) -> super::refusal::RevisionSyntax {
104        use super::refusal::RevisionSyntax;
105        match self {
106            Self::V1 => RevisionSyntax::V1Plan,
107            Self::Flags => RevisionSyntax::LegacyFlags,
108            Self::V2 => RevisionSyntax::V2Plan,
109            Self::Typed => RevisionSyntax::TypedAction,
110        }
111    }
112}
113
114/// What another author's revision did to the text it holds.
115#[derive(Clone, Copy, Debug, PartialEq, Eq)]
116pub(super) enum Held {
117    Inserted,
118    Deleted,
119    MovedHere,
120    MovedAway,
121    /// A tracked formatting change (`w:pPrChange`, `w:rPrChange`).
122    Formatted,
123}
124
125impl Held {
126    /// The kind of `node`, a `w:ins`, `w:del`, `w:moveTo`, `w:moveFrom`,
127    /// `w:pPrChange` or `w:rPrChange`.
128    pub(super) fn of(dom: &Dom, node: NodeId) -> Option<Self> {
129        [
130            ("ins", Self::Inserted),
131            ("del", Self::Deleted),
132            ("moveTo", Self::MovedHere),
133            ("moveFrom", Self::MovedAway),
134            ("pPrChange", Self::Formatted),
135            ("rPrChange", Self::Formatted),
136        ]
137        .into_iter()
138        .find(|(local, _)| dom.name_is(node, &W::name(local)))
139        .map(|(_, held)| held)
140    }
141
142    fn verb(self) -> &'static str {
143        match self {
144            Self::Inserted => "inserted",
145            Self::Deleted => "deleted",
146            Self::MovedHere => "moved here",
147            Self::MovedAway => "moved away",
148            Self::Formatted => "reformatted",
149        }
150    }
151
152    /// The noun a cost names: `erases "Bob"'s deletion`.
153    fn noun(self) -> &'static str {
154        match self {
155            Self::Inserted => "insertion",
156            Self::Deleted => "deletion",
157            Self::MovedHere | Self::MovedAway => "move",
158            Self::Formatted => "formatting",
159        }
160    }
161
162    /// The accept and reject routes, each with what it costs.
163    fn settles(self) -> [(&'static str, &'static str); 2] {
164        match self {
165            Self::Deleted => [
166                ("let it go", "their words leave the document for good"),
167                (
168                    "put it back silently",
169                    "their deletion disappears, no trace",
170                ),
171            ],
172            Self::Inserted => [
173                ("keep it", "their words stay, unmarked"),
174                (
175                    "take it out silently",
176                    "their insertion disappears, no trace",
177                ),
178            ],
179            Self::MovedHere | Self::MovedAway => [
180                ("keep the move", "the words stay where they moved, unmarked"),
181                (
182                    "undo it silently",
183                    "the words go back where they were, no trace",
184                ),
185            ],
186            Self::Formatted => [
187                ("keep their formatting", "their formatting stays, unmarked"),
188                (
189                    "undo it silently",
190                    "the old formatting comes back, no trace",
191                ),
192            ],
193        }
194    }
195}
196
197/// One revision a refused edit touched, as the hint names it.
198pub(super) struct Holder<'a> {
199    pub(super) held: Held,
200    /// The printed id (`r12`, `header1.r3`).
201    pub(super) id: &'a str,
202    /// The revision's long id, which a v2 plan's target carries.
203    pub(super) long_id: &'a str,
204    pub(super) author: &'a str,
205    /// The plan's author. Equal to `author` when the revision is your own.
206    pub(super) actor: &'a str,
207    /// [`super::Others::Keep`]: accept and reject are not offered for a
208    /// revision that is not your own.
209    pub(super) keep_others: bool,
210    /// The revision's text; empty for a paragraph mark.
211    pub(super) text: &'a str,
212    /// The printed id of the paragraph that holds it (`p160`).
213    pub(super) paragraph: &'a str,
214    /// What the refused edit touched, up to the revision's id: `the text is
215    /// inside`, `…cannot be merged: that mark is`.
216    pub(super) lead: &'a str,
217    /// Whether restore takes the revision, another author's deletion, as
218    /// [`super::visible::restorable`] decides.
219    pub(super) restorable: bool,
220}
221
222/// The `w:del` or `w:moveFrom` of `paragraph` whose text `find` reaches
223/// into, reading the paragraph's visible and removed text in document
224/// order, glyphs as the projection reads them (a tab as `\t`): an anchor
225/// copied from another author's deletion misses the visible text, and the
226/// hint should name the deletion, not the miss. The anchor matches as
227/// written, as it reads without marks, and with a deletion's marks
228/// unwrapped (`{--x--}` as `x`), each read past lookalike characters.
229pub(super) fn removed_holder(dom: &Dom, paragraph: NodeId, find: &str) -> Option<NodeId> {
230    if find.is_empty() {
231        return None;
232    }
233    let mut text = String::new();
234    let mut removed: Vec<(usize, usize, NodeId)> = Vec::new();
235    for node in dom.descendants(paragraph, None) {
236        // Text of a paragraph nested in a text box belongs to that one.
237        if !dom.parent(node).is_some_and(|r| dom.name_is(r, &W::r()))
238            || dom.ancestors(node, Some(&W::p())).first() != Some(&paragraph)
239        {
240            continue;
241        }
242        let Some(piece) = run_text(dom, node) else {
243            continue;
244        };
245        let start = text.len();
246        text.push_str(&piece);
247        let holder = dom
248            .ancestors(node, None)
249            .into_iter()
250            .find(|&a| matches!(Held::of(dom, a), Some(Held::Deleted | Held::MovedAway)));
251        if let Some(holder) = holder {
252            removed.push((start, text.len(), holder));
253        }
254    }
255    let plain = crate::markdown::plain_anchor(find);
256    let unwrapped = crate::markdown::plain_anchor_with_removed(find);
257    [find, plain.as_str(), unwrapped.as_str()]
258        .into_iter()
259        .flat_map(|needle| super::anchor::reading_hits(&text, needle))
260        .find_map(|(start, end)| {
261            removed
262                .iter()
263                .find(|&&(s, e, _)| s < end && start < e)
264                .map(|&(.., holder)| holder)
265        })
266}
267
268/// What a run child reads as in the paragraph's text: its text, or the
269/// character the projection gives a glyph; `None` for the rest.
270fn run_text(dom: &Dom, node: NodeId) -> Option<String> {
271    let local = dom.name(node).filter(|n| n.namespace_name() == W::URI)?;
272    let glyph = match local.local_name() {
273        "t" | "delText" => return Some(dom.value(node)),
274        "tab" | "ptab" => '\t',
275        "cr" => '\n',
276        "br" if !matches!(dom.attribute(node, &W::type_()), Some("page" | "column")) => '\n',
277        "noBreakHyphen" => '\u{2011}',
278        "softHyphen" => '\u{00ad}',
279        "sym" => '\u{fffc}',
280        _ => return None,
281    };
282    Some(glyph.to_string())
283}
284
285/// The longest stretch of a revision's text the hint quotes.
286const QUOTED: usize = 60;
287
288/// The refusal for an edit on text `holder` holds: what holds it, then
289/// accept, reject and a comment, each a fragment the caller can paste.
290///
291/// Another author's revision names what accepting or rejecting erases.
292/// With the guard on, those two routes are left out: a deletion offers
293/// restore, an insertion offers strike where the syntax has it, and a
294/// move or a formatting change says plainly that settling would erase it.
295pub(super) fn settle_hint(holder: &Holder<'_>, syntax: PlanSyntax) -> String {
296    let mut lines = vec![format!("{}.", named(holder))];
297    let foreign = holder.author != holder.actor;
298    let guard = holder.keep_others && foreign;
299    let noun = holder.held.noun();
300    let [accept, reject] = holder.held.settles();
301    let mut routes: Vec<(String, String, Option<&str>)> = Vec::new();
302    if guard {
303        if holder.held == Held::Inserted {
304            if let Some(quote) = strike(syntax, holder) {
305                routes.push((
306                    "strike it".to_string(),
307                    quote,
308                    Some("their insertion stays, your deletion shows"),
309                ));
310            }
311        } else if let Some(quote) = restore(syntax, holder) {
312            routes.push((
313                "put it back visibly".to_string(),
314                quote,
315                Some("their deletion stays, your insertion shows"),
316            ));
317        }
318    } else {
319        // Guard off, an insertion still offers the keeping move first,
320        // where this syntax can spell a strike. Accept and reject stay,
321        // and say what each one erases.
322        if holder.held == Held::Inserted
323            && foreign
324            && let Some(quote) = strike(syntax, holder)
325        {
326            routes.push((
327                "strike it".to_string(),
328                quote,
329                Some("their insertion stays, your deletion shows"),
330            ));
331        }
332        if let Some(quote) = restore(syntax, holder) {
333            routes.push((
334                "put it back visibly".to_string(),
335                quote,
336                Some("their deletion stays, your insertion shows"),
337            ));
338        }
339        routes.push((
340            route_name(accept.0, holder, noun),
341            settle(syntax, "accept", holder),
342            Some(accept.1),
343        ));
344        routes.push((
345            route_name(reject.0, holder, noun),
346            settle(syntax, "reject", holder),
347            Some(reject.1),
348        ));
349    }
350    // No restore and no strike: say so, without a colon, so it is not a route.
351    let bare = guard && routes.is_empty();
352    routes.push((
353        "or comment on it".to_string(),
354        comment(syntax, holder.paragraph),
355        None,
356    ));
357    let width = routes.iter().map(|r| r.0.len()).max().unwrap_or(0) + 1;
358    let fragment = routes
359        .iter()
360        .filter(|r| r.2.is_some())
361        .map(|r| r.1.chars().count())
362        .max()
363        .unwrap_or(0);
364    if bare {
365        lines.push("  accepting or rejecting would erase their change.".to_string());
366    }
367    for (name, quote, cost) in routes {
368        let name = format!("{name}:");
369        lines.push(match cost {
370            Some(cost) => {
371                let pad = " ".repeat(fragment - quote.chars().count());
372                format!("  {name:<width$} {quote}{pad} ({cost})")
373            }
374            None => format!("  {name:<width$} {quote}"),
375        });
376    }
377    lines.join("\n")
378}
379
380/// `base` as the route's name. Another author's revision says whose
381/// markup accepting or rejecting erases; your own keeps `base`.
382fn route_name(base: &str, holder: &Holder<'_>, noun: &str) -> String {
383    if holder.author == holder.actor {
384        base.to_string()
385    } else {
386        format!(r#"{base} (erases {:?}'s {noun})"#, holder.author)
387    }
388}
389
390/// The refusal of an edit inside a deletion the same command restores:
391/// the restore lands first, and the edit goes in a later command.
392pub(super) fn restored_here_hint(holder: &Holder<'_>) -> String {
393    format!(
394        "{}, which this command restores: edit the restored words in a command of their own, after the restore.",
395        named(holder)
396    )
397}
398
399/// The lead with the revision named: its id, text, what it did, by whom.
400fn named(holder: &Holder<'_>) -> String {
401    let text = if holder.text.is_empty() {
402        String::new()
403    } else {
404        format!("{} ", quoted(holder.text))
405    };
406    format!(
407        "{} {}, {text}{} by {:?}",
408        holder.lead,
409        holder.id,
410        holder.held.verb(),
411        holder.author
412    )
413}
414
415/// The target a v2 comment route names until [`super::v2_apply`] writes in
416/// the refused operation's own: valid JSON, left to fill in like `find`.
417pub(super) const OPERATION_TARGET: &str = r#"{"short_id":"…","long_id":"…"}"#;
418
419/// `text` as a JSON string, quotes and backslashes escaped.
420fn json(text: &str) -> String {
421    serde_json::Value::from(text).to_string()
422}
423
424/// The strike of an insertion, as `syntax` spells it. The typed commands
425/// have no strike yet.
426fn strike(syntax: PlanSyntax, holder: &Holder<'_>) -> Option<String> {
427    if holder.held != Held::Inserted {
428        return None;
429    }
430    match syntax {
431        PlanSyntax::V1 => Some(format!(
432            r#"{{"kind":"strike","revision":{}}}"#,
433            json(holder.id)
434        )),
435        PlanSyntax::Flags => Some(format!("-p {} --strike", shell_word(holder.id))),
436        PlanSyntax::V2 => Some(format!(
437            r#"{{"kind":"strike","target":{{"short_id":{},"long_id":{}}}}}"#,
438            json(holder.id),
439            json(holder.long_id)
440        )),
441        PlanSyntax::Typed => None,
442    }
443}
444
445/// The restore of the revision, as `syntax` spells it: offered for a
446/// deletion with words restore takes, in a syntax that has it.
447fn restore(syntax: PlanSyntax, holder: &Holder<'_>) -> Option<String> {
448    if holder.held != Held::Deleted || !holder.restorable || holder.text.is_empty() {
449        return None;
450    }
451    match syntax {
452        PlanSyntax::V1 => Some(format!(
453            r#"{{"kind":"restore","revision":{}}}"#,
454            json(holder.id)
455        )),
456        PlanSyntax::Flags => Some(format!("-p {} --restore", shell_word(holder.id))),
457        PlanSyntax::V2 => Some(format!(
458            r#"{{"kind":"restore","target":{{"short_id":{},"long_id":{}}}}}"#,
459            json(holder.id),
460            json(holder.long_id)
461        )),
462        // The typed commands have no restore yet.
463        PlanSyntax::Typed => None,
464    }
465}
466
467/// `id` as one shell word. A short id prints bare; a colon id carries the
468/// document's `w:id` verbatim (`body:rev:1;x`), so it is single-quoted when
469/// a shell would read anything in it.
470fn shell_word(id: &str) -> std::borrow::Cow<'_, str> {
471    let bare = !id.is_empty()
472        && !id.starts_with(['#', '=', '~', '-'])
473        && id
474            .bytes()
475            .all(|b| b.is_ascii_alphanumeric() || b"._%:+-".contains(&b));
476    if bare {
477        id.into()
478    } else {
479        format!("'{}'", id.replace('\'', r"'\''")).into()
480    }
481}
482
483/// `verb` (`accept` or `reject`) of the revision, as `syntax` spells it.
484fn settle(syntax: PlanSyntax, verb: &str, holder: &Holder<'_>) -> String {
485    settle_revision(syntax, verb, holder.id, holder.long_id)
486}
487
488fn settle_revision(syntax: PlanSyntax, verb: &str, id: &str, long_id: &str) -> String {
489    match syntax {
490        PlanSyntax::V1 => format!(
491            r#""resolve_revisions":{{"{verb}":{{"ids":[{}]}}}}"#,
492            json(id)
493        ),
494        PlanSyntax::Flags => format!("-p {} --{verb}", shell_word(id)),
495        // Added to the refused command itself, which settles before it edits.
496        PlanSyntax::Typed => format!("--{verb}-change {}", shell_word(id)),
497        // A v2 plan's resolve_revisions names both lists.
498        PlanSyntax::V2 => {
499            let target = format!(
500                r#"[{{"short_id":{},"long_id":{}}}]"#,
501                json(id),
502                json(long_id)
503            );
504            let (accept, reject) = if verb == "accept" {
505                (target.as_str(), "[]")
506            } else {
507                ("[]", target.as_str())
508            };
509            format!(r#""resolve_revisions":{{"accept":{accept},"reject":{reject}}}"#)
510        }
511    }
512}
513
514/// A comment on the paragraph, as `syntax` spells it; a paragraph the
515/// hint could not name is left to fill in.
516fn comment(syntax: PlanSyntax, paragraph: &str) -> String {
517    let paragraph = if paragraph.is_empty() {
518        "…"
519    } else {
520        paragraph
521    };
522    match syntax {
523        PlanSyntax::V1 => format!(
524            r#"{{"kind":"comment","paragraph":{},"find":"…","text":"…"}}"#,
525            json(paragraph)
526        ),
527        // The typed commands have no comment of their own; `add` is the
528        // command line's.
529        PlanSyntax::Flags | PlanSyntax::Typed => {
530            format!(r#"add -p {paragraph} --anchor "…" --content "…""#)
531        }
532        PlanSyntax::V2 => {
533            format!(r#"{{"kind":"comment","target":{OPERATION_TARGET},"find":"…","text":"…"}}"#)
534        }
535    }
536}
537
538/// `text` in quotes, cut to [`QUOTED`] characters with the cut said.
539fn quoted(text: &str) -> String {
540    if text.chars().count() <= QUOTED {
541        return format!("{text:?}");
542    }
543    let head: String = text.chars().take(QUOTED).collect();
544    format!("{head:?}…")
545}
546
547#[cfg(test)]
548mod tests {
549    use super::*;
550
551    fn holder(held: Held) -> Holder<'static> {
552        Holder {
553            held,
554            id: "r12",
555            long_id: "document.w:del.w:id.12",
556            author: "Bob Lee",
557            actor: "Bob Lee",
558            keep_others: false,
559            text: "the bankers",
560            paragraph: "p3",
561            lead: "the text is inside",
562            restorable: held == Held::Deleted,
563        }
564    }
565
566    #[test]
567    fn a_deletion_offers_restore_first_then_both_settles_then_comment() {
568        assert_eq!(
569            settle_hint(&holder(Held::Deleted), PlanSyntax::V1),
570            [
571                r#"the text is inside r12, "the bankers" deleted by "Bob Lee"."#,
572                r#"  put it back visibly:  {"kind":"restore","revision":"r12"}            (their deletion stays, your insertion shows)"#,
573                r#"  let it go:            "resolve_revisions":{"accept":{"ids":["r12"]}} (their words leave the document for good)"#,
574                r#"  put it back silently: "resolve_revisions":{"reject":{"ids":["r12"]}} (their deletion disappears, no trace)"#,
575                r#"  or comment on it:     {"kind":"comment","paragraph":"p3","find":"…","text":"…"}"#,
576            ]
577            .join("\n")
578        );
579    }
580
581    /// A colon id carries the document's `w:id` verbatim (`body:rev:1;x`), so
582    /// the command fragments quote it for the shell (review gid=54).
583    #[test]
584    fn a_colon_id_with_shell_syntax_is_quoted_in_command_fragments() {
585        let mut odd = holder(Held::Deleted);
586        odd.id = "body:rev:1;touch x";
587        let flags = settle_hint(&odd, PlanSyntax::Flags);
588        assert!(
589            flags.contains("-p 'body:rev:1;touch x' --restore"),
590            "{flags}"
591        );
592        assert!(
593            flags.contains("-p 'body:rev:1;touch x' --accept"),
594            "{flags}"
595        );
596        assert!(
597            flags.contains("-p 'body:rev:1;touch x' --reject"),
598            "{flags}"
599        );
600        let typed = settle_hint(&odd, PlanSyntax::Typed);
601        assert!(
602            typed.contains("--accept-change 'body:rev:1;touch x'"),
603            "{typed}"
604        );
605        odd.id = "body:rev:it's";
606        let flags = settle_hint(&odd, PlanSyntax::Flags);
607        assert!(
608            flags.contains(r#"-p 'body:rev:it'\''s' --accept"#),
609            "{flags}"
610        );
611        // A shell-safe id prints bare, as before.
612        assert!(settle_hint(&holder(Held::Deleted), PlanSyntax::Flags).contains("-p r12 --accept"));
613    }
614
615    #[test]
616    fn each_syntax_quotes_its_own_fragments() {
617        for syntax in PlanSyntax::ALL {
618            let hint = settle_hint(&holder(Held::Deleted), syntax);
619            let (wanted, foreign): (&[&str], &[&str]) = match syntax {
620                PlanSyntax::V1 => (
621                    &[
622                        r#"{"ids":["r12"]}"#,
623                        r#""paragraph":"p3""#,
624                        r#"{"kind":"restore","revision":"r12"}"#,
625                    ],
626                    &["--accept", "short_id"],
627                ),
628                PlanSyntax::Flags => (
629                    &[
630                        "-p r12 --restore",
631                        "-p r12 --accept",
632                        "-p r12 --reject",
633                        "add -p p3 --anchor",
634                    ],
635                    &["resolve_revisions"],
636                ),
637                PlanSyntax::V2 => (
638                    &[
639                        r#""accept":[{"short_id":"r12","long_id":"document.w:del.w:id.12"}]"#,
640                        r#""target":"#,
641                        r#"{"kind":"restore","target":{"short_id":"r12","long_id":"document.w:del.w:id.12"}}"#,
642                    ],
643                    &[r#""ids""#, "--accept", r#""paragraph""#],
644                ),
645                PlanSyntax::Typed => (
646                    &[
647                        "--accept-change r12",
648                        "--reject-change r12",
649                        "add -p p3 --anchor",
650                    ],
651                    &["resolve_revisions", "-p r12"],
652                ),
653            };
654            for want in wanted {
655                assert!(hint.contains(want), "{syntax:?} lacks {want}: {hint}");
656            }
657            for not in foreign {
658                assert!(!hint.contains(not), "{syntax:?} quotes {not}: {hint}");
659            }
660        }
661    }
662
663    #[test]
664    fn every_kind_names_what_the_revision_did() {
665        for (held, says, first) in [
666            (Held::Inserted, "inserted by", "keep it:"),
667            (Held::Deleted, "deleted by", "put it back visibly:"),
668            (Held::MovedHere, "moved here by", "keep the move:"),
669            (Held::MovedAway, "moved away by", "keep the move:"),
670            (Held::Formatted, "reformatted by", "keep their formatting:"),
671        ] {
672            let hint = settle_hint(&holder(held), PlanSyntax::V1);
673            assert!(hint.lines().next().unwrap().contains(says), "{hint}");
674            assert!(
675                hint.lines().nth(1).unwrap().trim_start().starts_with(first),
676                "{hint}"
677            );
678            assert!(!hint.contains("settle it first"), "{hint}");
679        }
680    }
681
682    #[test]
683    fn a_deletion_restore_cannot_take_offers_no_visible_route() {
684        let hint = settle_hint(
685            &Holder {
686                restorable: false,
687                ..holder(Held::Deleted)
688            },
689            PlanSyntax::V1,
690        );
691        assert_eq!(hint.lines().count(), 4, "{hint}");
692        assert!(!hint.contains("restore"), "{hint}");
693    }
694
695    #[test]
696    fn the_restore_route_parses_whatever_the_id_holds() {
697        let odd = Holder {
698            id: r#"r"1\2"#,
699            ..holder(Held::Deleted)
700        };
701        let hint = settle_hint(&odd, PlanSyntax::V1);
702        let line = hint.lines().nth(1).unwrap();
703        let route: serde_json::Value = serde_json::from_str(fragment(line))
704            .unwrap_or_else(|e| panic!("not JSON ({e}): {hint}"));
705        assert_eq!(
706            route,
707            serde_json::json!({"kind":"restore","revision": odd.id})
708        );
709    }
710
711    #[test]
712    fn a_mark_without_text_is_named_without_quotes() {
713        let hint = settle_hint(
714            &Holder {
715                text: "",
716                lead: "that mark is",
717                ..holder(Held::Inserted)
718            },
719            PlanSyntax::V1,
720        );
721        assert_eq!(
722            hint.lines().next().unwrap(),
723            r#"that mark is r12, inserted by "Bob Lee"."#
724        );
725    }
726
727    /// A route line's fragment: what follows its label, without the cost.
728    fn fragment(line: &str) -> &str {
729        let rest = line.split_once(':').map_or(line, |(_, r)| r).trim_start();
730        rest.rsplit_once(" (").map_or(rest, |(f, _)| f.trim_end())
731    }
732
733    /// The route lines of `hint` as JSON: accept, reject, comment (the
734    /// last three, after any visible route).
735    fn routes(hint: &str) -> [serde_json::Value; 3] {
736        let all: Vec<&str> = hint.lines().collect();
737        let lines = &all[all.len() - 4..];
738        let parse = |s: String| {
739            serde_json::from_str(&s).unwrap_or_else(|e| panic!("{s} is not JSON ({e}): {hint}"))
740        };
741        [
742            parse(format!("{{{}}}", fragment(lines[1]))),
743            parse(format!("{{{}}}", fragment(lines[2]))),
744            parse(fragment(lines[3]).to_string()),
745        ]
746    }
747
748    #[test]
749    fn every_json_route_parses_whatever_the_ids_hold() {
750        let odd = Holder {
751            id: r#"r"1\2"#,
752            long_id: r#"document.w:del.w:id."1\2"#,
753            paragraph: r#"p"3\"#,
754            ..holder(Held::Deleted)
755        };
756        let [accept, reject, comment] = routes(&settle_hint(&odd, PlanSyntax::V1));
757        assert_eq!(accept["resolve_revisions"]["accept"]["ids"][0], odd.id);
758        assert_eq!(reject["resolve_revisions"]["reject"]["ids"][0], odd.id);
759        assert_eq!(comment["paragraph"], odd.paragraph);
760        let [accept, reject, comment] = routes(&settle_hint(&odd, PlanSyntax::V2));
761        let target = serde_json::json!({"short_id": odd.id, "long_id": odd.long_id});
762        assert_eq!(accept["resolve_revisions"]["accept"][0], target);
763        assert_eq!(reject["resolve_revisions"]["reject"][0], target);
764        assert_eq!(comment["kind"], "comment");
765    }
766
767    #[test]
768    fn v2_routes_parse_as_the_plan_v2_types() {
769        let hint = settle_hint(&holder(Held::Deleted), PlanSyntax::V2);
770        let [accept, reject, comment] = routes(&hint);
771        for route in [accept, reject] {
772            serde_json::from_value::<super::super::v2::RevisionDecisions>(
773                route["resolve_revisions"].clone(),
774            )
775            .unwrap_or_else(|e| panic!("{route} is no resolve_revisions ({e}): {hint}"));
776        }
777        serde_json::from_value::<super::super::v2::Operation>(comment.clone())
778            .unwrap_or_else(|e| panic!("{comment} is no operation ({e}): {hint}"));
779    }
780
781    #[test]
782    fn a_paragraph_the_hint_cannot_name_is_left_to_fill_in() {
783        let lost = Holder {
784            paragraph: "",
785            ..holder(Held::Deleted)
786        };
787        let v1 = settle_hint(&lost, PlanSyntax::V1);
788        let [.., comment] = routes(&v1);
789        assert_eq!(comment["paragraph"], "…", "{v1}");
790        let flags = settle_hint(&lost, PlanSyntax::Flags);
791        assert!(
792            flags
793                .lines()
794                .last()
795                .unwrap()
796                .ends_with(r#"add -p … --anchor "…" --content "…""#),
797            "{flags}"
798        );
799    }
800
801    #[test]
802    fn a_long_revision_is_quoted_with_the_cut_said() {
803        let text = "x".repeat(QUOTED + 5);
804        let hint = settle_hint(
805            &Holder {
806                text: &text,
807                ..holder(Held::Deleted)
808            },
809            PlanSyntax::V1,
810        );
811        assert!(
812            hint.contains(&format!("\"{}\"…", "x".repeat(QUOTED))),
813            "{hint}"
814        );
815    }
816
817    /// Another author's revision: the plan author is not Bob Lee.
818    fn foreign(held: Held) -> Holder<'static> {
819        Holder {
820            author: "Trainer 1 - AgentCo",
821            actor: "Jubarte",
822            keep_others: false,
823            ..holder(held)
824        }
825    }
826
827    #[test]
828    fn hint_names_the_cost_of_erasing_another_authors_deletion_in_every_syntax() {
829        for syntax in PlanSyntax::ALL {
830            let hint = settle_hint(&foreign(Held::Deleted), syntax);
831            assert!(
832                hint.contains(r#"let it go (erases "Trainer 1 - AgentCo"'s deletion):"#),
833                "{syntax:?}\n{hint}"
834            );
835            assert!(
836                hint.contains(r#"put it back silently (erases "Trainer 1 - AgentCo"'s deletion):"#),
837                "{syntax:?}\n{hint}"
838            );
839        }
840    }
841
842    #[test]
843    fn hint_names_the_cost_of_erasing_another_authors_insertion_move_and_formatting() {
844        for (held, first, noun) in [
845            (Held::Inserted, "keep it", "insertion"),
846            (Held::MovedHere, "keep the move", "move"),
847            (Held::MovedAway, "undo it silently", "move"),
848            (Held::Formatted, "keep their formatting", "formatting"),
849        ] {
850            let hint = settle_hint(&foreign(held), PlanSyntax::V1);
851            let label = format!(r#"{first} (erases "Trainer 1 - AgentCo"'s {noun}):"#);
852            assert!(hint.contains(&label), "{hint}");
853        }
854    }
855
856    #[test]
857    fn hint_guard_on_drops_accept_and_reject_for_another_author_in_every_syntax() {
858        for syntax in PlanSyntax::ALL {
859            let guarded = Holder {
860                keep_others: true,
861                ..foreign(Held::Deleted)
862            };
863            let hint = settle_hint(&guarded, syntax);
864            assert!(
865                !hint.contains("--accept")
866                    && !hint.contains("\"accept\"")
867                    && !hint.contains("--reject")
868                    && !hint.contains("\"reject\"")
869                    && !hint.contains("--accept-change")
870                    && !hint.contains("--reject-change"),
871                "{syntax:?}\n{hint}"
872            );
873            match syntax {
874                PlanSyntax::V1 | PlanSyntax::Flags | PlanSyntax::V2 => {
875                    assert!(hint.contains("restore"), "{syntax:?}\n{hint}");
876                }
877                PlanSyntax::Typed => {
878                    assert!(
879                        hint.contains("accepting or rejecting would erase their change"),
880                        "{syntax:?}\n{hint}"
881                    );
882                    assert!(!hint.contains("restore"), "{syntax:?}\n{hint}");
883                }
884            }
885        }
886    }
887
888    #[test]
889    fn hint_guard_off_offers_strike_first_for_another_authors_insertion() {
890        for syntax in [PlanSyntax::V1, PlanSyntax::Flags, PlanSyntax::V2] {
891            let hint = settle_hint(&foreign(Held::Inserted), syntax);
892            let routes: Vec<&str> = hint.lines().skip(1).collect();
893            assert!(
894                routes[0].contains("strike it")
895                    && routes[0].contains("their insertion stays, your deletion shows"),
896                "{syntax:?}\n{hint}"
897            );
898            assert!(
899                hint.contains(r#"keep it (erases "Trainer 1 - AgentCo"'s insertion):"#),
900                "{syntax:?}\n{hint}"
901            );
902            assert!(
903                hint.contains(
904                    r#"take it out silently (erases "Trainer 1 - AgentCo"'s insertion):"#
905                ),
906                "{syntax:?}\n{hint}"
907            );
908        }
909        let typed = settle_hint(&foreign(Held::Inserted), PlanSyntax::Typed);
910        assert!(!typed.lines().nth(1).unwrap().contains("strike"), "{typed}");
911        assert!(
912            typed.contains(r#"keep it (erases "Trainer 1 - AgentCo"'s insertion):"#),
913            "{typed}"
914        );
915        let own = settle_hint(&holder(Held::Inserted), PlanSyntax::V1);
916        assert!(!own.contains("strike"), "{own}");
917    }
918
919    #[test]
920    fn hint_guard_on_strikes_an_insertion_where_the_syntax_has_strike() {
921        let guarded = Holder {
922            keep_others: true,
923            ..foreign(Held::Inserted)
924        };
925        let v1 = settle_hint(&guarded, PlanSyntax::V1);
926        assert!(v1.contains(r#"{"kind":"strike","revision":"r12"}"#), "{v1}");
927        assert!(!v1.contains("resolve_revisions"), "{v1}");
928        let flags = settle_hint(&guarded, PlanSyntax::Flags);
929        assert!(flags.contains("-p r12 --strike"), "{flags}");
930        assert!(
931            !flags.contains("--accept") && !flags.contains("--reject"),
932            "{flags}"
933        );
934        let v2 = settle_hint(&guarded, PlanSyntax::V2);
935        assert!(
936            v2.contains(
937                r#"{"kind":"strike","target":{"short_id":"r12","long_id":"document.w:del.w:id.12"}}"#
938            ),
939            "{v2}"
940        );
941        assert!(!v2.contains("resolve_revisions"), "{v2}");
942        let typed = settle_hint(&guarded, PlanSyntax::Typed);
943        assert!(
944            typed.contains("accepting or rejecting would erase their change"),
945            "{typed}"
946        );
947        assert!(!typed.contains("strike"), "{typed}");
948        assert!(!typed.contains("resolve_revisions"), "{typed}");
949    }
950
951    #[test]
952    fn hint_guard_on_offers_only_a_comment_for_another_authors_move() {
953        let guarded = Holder {
954            keep_others: true,
955            ..foreign(Held::MovedHere)
956        };
957        for syntax in PlanSyntax::ALL {
958            let hint = settle_hint(&guarded, syntax);
959            assert!(
960                hint.contains("accepting or rejecting would erase their change"),
961                "{syntax:?}\n{hint}"
962            );
963            assert!(
964                !hint.contains("resolve_revisions")
965                    && !hint.contains("--accept")
966                    && !hint.contains("--reject-change"),
967                "{syntax:?}\n{hint}"
968            );
969        }
970    }
971
972    #[test]
973    fn hint_guard_on_keeps_the_four_routes_for_your_own_deletion() {
974        let own = Holder {
975            keep_others: true,
976            ..holder(Held::Deleted)
977        };
978        let hint = settle_hint(&own, PlanSyntax::V1);
979        assert!(hint.contains("  let it go:"), "{hint}");
980        assert!(hint.contains("  put it back silently:"), "{hint}");
981        assert!(!hint.contains("erases"), "{hint}");
982    }
983}
984
985#[cfg(test)]
986#[cfg_attr(all(coverage_nightly, test), coverage(off))]
987mod holder_branch_tests {
988    use super::*;
989
990    #[test]
991    fn flags_list_each_occurrence_with_cut_marks_on_long_sides() {
992        let text = "x long words before the anchor here and then many more words after anchor";
993        let hits: Vec<(usize, usize)> = text
994            .match_indices("anchor")
995            .map(|(s, a)| (s, s + a.len()))
996            .collect();
997        let message = PlanSyntax::Flags.ambiguous_anchor(text, "anchor", &hits);
998        assert!(message.contains("occurs 2 times"), "{message}");
999        assert!(message.contains("--occurrence 1..=2"), "{message}");
1000        let lines: Vec<&str> = message.lines().filter(|l| l.starts_with("  ")).collect();
1001        assert_eq!(lines.len(), 2, "{message}");
1002        // The first hit has over 20 chars on both sides, the last none after.
1003        assert!(lines[0].contains('…'), "{message}");
1004        assert!(!lines[1].trim_end().ends_with("…\""), "{message}");
1005        let near = PlanSyntax::Flags.ambiguous_anchor("ab x ab", "ab", &[(0, 2), (5, 7)]);
1006        assert!(!near.contains('…'), "{near}");
1007        let short = PlanSyntax::V1.ambiguous_anchor("ab ab", "ab", &[(0, 2), (3, 5)]);
1008        assert!(short.contains("\"occurrence\" to 1..=2"), "{short}");
1009        assert!(!short.contains("\n  1:"), "{short}");
1010    }
1011
1012    fn paragraph(xml: &str) -> (Dom, NodeId) {
1013        let mut dom = Dom::new();
1014        let doc = dom.parse_xdocument(&format!(r#"<w:p xmlns:w="{}">{xml}</w:p>"#, W::URI));
1015        let p = dom.root(doc).unwrap();
1016        (dom, p)
1017    }
1018
1019    #[test]
1020    fn removed_holder_finds_the_deletion_an_anchor_reaches_into() {
1021        let (dom, p) = paragraph(
1022            r#"<w:r><w:t xml:space="preserve">Keep </w:t><w:tab/><w:br w:type="page"/><w:br/><w:cr/><w:noBreakHyphen/><w:softHyphen/><w:sym w:char="F0E0"/><w:lastRenderedPageBreak/></w:r><w:del w:id="3" w:author="Bo"><w:r><w:delText>gone words</w:delText></w:r></w:del><w:r><w:pict><w:p><w:r><w:t>boxed gone</w:t></w:r></w:p></w:pict></w:r>"#,
1023        );
1024        let del = dom.descendants(p, Some(&W::del()))[0];
1025        assert_eq!(removed_holder(&dom, p, "gone words"), Some(del));
1026        assert_eq!(removed_holder(&dom, p, "{--gone--}"), Some(del));
1027        assert_eq!(
1028            removed_holder(&dom, p, "\n\u{2011}\u{ad}\u{fffc}gone"),
1029            Some(del)
1030        );
1031        assert_eq!(removed_holder(&dom, p, "Keep"), None);
1032        assert_eq!(removed_holder(&dom, p, "boxed"), None);
1033        assert_eq!(removed_holder(&dom, p, ""), None);
1034    }
1035
1036    fn holder<'a>(held: Held, restorable: bool, text: &'a str) -> Holder<'a> {
1037        Holder {
1038            held,
1039            id: "r3",
1040            long_id: "body:rev:3",
1041            author: "Bo",
1042            actor: "Ed",
1043            keep_others: true,
1044            text,
1045            paragraph: "p0",
1046            lead: "the text is inside",
1047            restorable,
1048        }
1049    }
1050
1051    #[test]
1052    fn strike_and_restore_fragments_follow_the_kind_and_syntax() {
1053        let ins = holder(Held::Inserted, false, "new");
1054        let del = holder(Held::Deleted, true, "old");
1055        for syntax in PlanSyntax::ALL {
1056            let has = syntax != PlanSyntax::Typed;
1057            assert_eq!(strike(syntax, &ins).is_some(), has, "{syntax:?}");
1058            assert_eq!(restore(syntax, &del).is_some(), has, "{syntax:?}");
1059            assert_eq!(strike(syntax, &del), None);
1060            assert_eq!(restore(syntax, &ins), None);
1061            assert_eq!(restore(syntax, &holder(Held::Deleted, false, "old")), None);
1062            assert_eq!(restore(syntax, &holder(Held::Deleted, true, "")), None);
1063        }
1064        assert_eq!(strike(PlanSyntax::Flags, &ins).unwrap(), "-p r3 --strike");
1065        assert_eq!(shell_word(""), "''");
1066        assert_eq!(shell_word("#x"), "'#x'");
1067        assert_eq!(shell_word("a b"), "'a b'");
1068        assert_eq!(shell_word("it's"), r"'it'\''s'");
1069        assert_eq!(shell_word("body:rev:1"), "body:rev:1");
1070    }
1071}