jubarte-edit 0.20.0

The edit product of the jubarte engine: edit plans as tracked changes, text diff views, capabilities and staged publication
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
//
// SPDX-License-Identifier: Apache-2.0

//! What a refusal says when another author's revision holds the text
//! (#1108): the revision by id, author and text, then each way around it
//! with what that way costs, quoted in the syntax the caller wrote.

use crate::namespaces::W;
use crate::xmllinq::{Dom, NodeId};

/// The request syntax a refusal quotes, so a hint never names a form the
/// caller's parser would reject.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum PlanSyntax {
    /// A `schema_version: 1` JSON plan (`edit --plan`, the library).
    #[default]
    V1,
    /// The operation flags (`edit FILE -p p3 --anchor … --content …`).
    Flags,
    /// A `schema_version: 2` plan (`edit apply`).
    V2,
    /// The typed commands (`edit replace FILE --at p3 --find … --text …`),
    /// which take their decisions as `--accept-change` / `--reject-change`.
    Typed,
}

impl PlanSyntax {
    /// Every syntax, for the tests that check each one's fragments.
    pub const ALL: [Self; 4] = [Self::V1, Self::Flags, Self::V2, Self::Typed];

    /// A partial change selection, with the whole-change retry in the
    /// caller's flags. Plans retain their released wording (#1895).
    pub(super) fn incomplete_change(
        self,
        error: &crate::changes::ChangeError,
        verb: &str,
    ) -> String {
        if let (
            Self::Flags | Self::Typed,
            crate::changes::ChangeError::PartOfChange { named, whole, .. },
        ) = (self, error)
        {
            format!(
                "{named} is part of {whole}; name the whole change: {}",
                settle_revision(self, verb, whole, "")
            )
        } else {
            format!("resolve_revisions: {error}")
        }
    }

    /// Selection errors quote plan fields only for a plan caller.
    pub(super) fn selection_message(self, message: impl std::fmt::Display) -> String {
        match self {
            Self::V1 | Self::V2 => format!("resolve_revisions: {message}"),
            Self::Flags | Self::Typed => message.to_string(),
        }
    }

    /// Quote the occurrence selector in the caller's grammar. Plans retain
    /// #1013's released wording; one-shot flags also show every candidate.
    pub(super) fn ambiguous_anchor(
        self,
        text: &str,
        anchor: &str,
        hits: &[(usize, usize)],
    ) -> String {
        let shown = super::anchor::shown(anchor);
        let n = hits.len();
        let selector = match self {
            Self::Flags | Self::Typed => format!("set --occurrence 1..={n}"),
            Self::V1 | Self::V2 => format!("set \"occurrence\" to 1..={n}"),
        };
        let mut message = format!("{shown} occurs {n} times in the paragraph; {selector}");
        if self == Self::Flags {
            for (i, &(start, end)) in hits.iter().enumerate() {
                let before = if text[..start].chars().nth_back(20).is_some() {
                    "…"
                } else {
                    ""
                };
                let after = if text[end..].chars().nth(20).is_some() {
                    "…"
                } else {
                    ""
                };
                let window = super::context(text, start, end, &text[start..end]);
                message.push_str(&format!(
                    "\n  {}: {}",
                    i + 1,
                    super::anchor::shown(&format!("{before}{window}{after}"))
                ));
            }
            message.push_str(
                "\nlengthen --anchor to the words around the one you mean, or pass --occurrence",
            );
        }
        message
    }

    /// The same choice as a refusal's data records it.
    pub(super) const fn revision(self) -> super::refusal::RevisionSyntax {
        use super::refusal::RevisionSyntax;
        match self {
            Self::V1 => RevisionSyntax::V1Plan,
            Self::Flags => RevisionSyntax::LegacyFlags,
            Self::V2 => RevisionSyntax::V2Plan,
            Self::Typed => RevisionSyntax::TypedAction,
        }
    }
}

/// What another author's revision did to the text it holds.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Held {
    Inserted,
    Deleted,
    MovedHere,
    MovedAway,
    /// A tracked formatting change (`w:pPrChange`, `w:rPrChange`).
    Formatted,
}

impl Held {
    /// The kind of `node`, a `w:ins`, `w:del`, `w:moveTo`, `w:moveFrom`,
    /// `w:pPrChange` or `w:rPrChange`.
    pub(super) fn of(dom: &Dom, node: NodeId) -> Option<Self> {
        [
            ("ins", Self::Inserted),
            ("del", Self::Deleted),
            ("moveTo", Self::MovedHere),
            ("moveFrom", Self::MovedAway),
            ("pPrChange", Self::Formatted),
            ("rPrChange", Self::Formatted),
        ]
        .into_iter()
        .find(|(local, _)| dom.name_is(node, &W::name(local)))
        .map(|(_, held)| held)
    }

    fn verb(self) -> &'static str {
        match self {
            Self::Inserted => "inserted",
            Self::Deleted => "deleted",
            Self::MovedHere => "moved here",
            Self::MovedAway => "moved away",
            Self::Formatted => "reformatted",
        }
    }

    /// The noun a cost names: `erases "Bob"'s deletion`.
    fn noun(self) -> &'static str {
        match self {
            Self::Inserted => "insertion",
            Self::Deleted => "deletion",
            Self::MovedHere | Self::MovedAway => "move",
            Self::Formatted => "formatting",
        }
    }

    /// The accept and reject routes, each with what it costs.
    fn settles(self) -> [(&'static str, &'static str); 2] {
        match self {
            Self::Deleted => [
                ("let it go", "their words leave the document for good"),
                (
                    "put it back silently",
                    "their deletion disappears, no trace",
                ),
            ],
            Self::Inserted => [
                ("keep it", "their words stay, unmarked"),
                (
                    "take it out silently",
                    "their insertion disappears, no trace",
                ),
            ],
            Self::MovedHere | Self::MovedAway => [
                ("keep the move", "the words stay where they moved, unmarked"),
                (
                    "undo it silently",
                    "the words go back where they were, no trace",
                ),
            ],
            Self::Formatted => [
                ("keep their formatting", "their formatting stays, unmarked"),
                (
                    "undo it silently",
                    "the old formatting comes back, no trace",
                ),
            ],
        }
    }
}

/// One revision a refused edit touched, as the hint names it.
pub(super) struct Holder<'a> {
    pub(super) held: Held,
    /// The printed id (`r12`, `header1.r3`).
    pub(super) id: &'a str,
    /// The revision's long id, which a v2 plan's target carries.
    pub(super) long_id: &'a str,
    pub(super) author: &'a str,
    /// The plan's author. Equal to `author` when the revision is your own.
    pub(super) actor: &'a str,
    /// [`super::Others::Keep`]: accept and reject are not offered for a
    /// revision that is not your own.
    pub(super) keep_others: bool,
    /// The revision's text; empty for a paragraph mark.
    pub(super) text: &'a str,
    /// The printed id of the paragraph that holds it (`p160`).
    pub(super) paragraph: &'a str,
    /// What the refused edit touched, up to the revision's id: `the text is
    /// inside`, `…cannot be merged: that mark is`.
    pub(super) lead: &'a str,
    /// Whether restore takes the revision, another author's deletion, as
    /// [`super::visible::restorable`] decides.
    pub(super) restorable: bool,
}

/// The `w:del` or `w:moveFrom` of `paragraph` whose text `find` reaches
/// into, reading the paragraph's visible and removed text in document
/// order, glyphs as the projection reads them (a tab as `\t`): an anchor
/// copied from another author's deletion misses the visible text, and the
/// hint should name the deletion, not the miss. The anchor matches as
/// written, as it reads without marks, and with a deletion's marks
/// unwrapped (`{--x--}` as `x`), each read past lookalike characters.
pub(super) fn removed_holder(dom: &Dom, paragraph: NodeId, find: &str) -> Option<NodeId> {
    if find.is_empty() {
        return None;
    }
    let mut text = String::new();
    let mut removed: Vec<(usize, usize, NodeId)> = Vec::new();
    for node in dom.descendants(paragraph, None) {
        // Text of a paragraph nested in a text box belongs to that one.
        if !dom.parent(node).is_some_and(|r| dom.name_is(r, &W::r()))
            || dom.ancestors(node, Some(&W::p())).first() != Some(&paragraph)
        {
            continue;
        }
        let Some(piece) = run_text(dom, node) else {
            continue;
        };
        let start = text.len();
        text.push_str(&piece);
        let holder = dom
            .ancestors(node, None)
            .into_iter()
            .find(|&a| matches!(Held::of(dom, a), Some(Held::Deleted | Held::MovedAway)));
        if let Some(holder) = holder {
            removed.push((start, text.len(), holder));
        }
    }
    let plain = crate::markdown::plain_anchor(find);
    let unwrapped = crate::markdown::plain_anchor_with_removed(find);
    [find, plain.as_str(), unwrapped.as_str()]
        .into_iter()
        .flat_map(|needle| super::anchor::reading_hits(&text, needle))
        .find_map(|(start, end)| {
            removed
                .iter()
                .find(|&&(s, e, _)| s < end && start < e)
                .map(|&(.., holder)| holder)
        })
}

/// What a run child reads as in the paragraph's text: its text, or the
/// character the projection gives a glyph; `None` for the rest.
fn run_text(dom: &Dom, node: NodeId) -> Option<String> {
    let local = dom.name(node).filter(|n| n.namespace_name() == W::URI)?;
    let glyph = match local.local_name() {
        "t" | "delText" => return Some(dom.value(node)),
        "tab" | "ptab" => '\t',
        "cr" => '\n',
        "br" if !matches!(dom.attribute(node, &W::type_()), Some("page" | "column")) => '\n',
        "noBreakHyphen" => '\u{2011}',
        "softHyphen" => '\u{00ad}',
        "sym" => '\u{fffc}',
        _ => return None,
    };
    Some(glyph.to_string())
}

/// The longest stretch of a revision's text the hint quotes.
const QUOTED: usize = 60;

/// The refusal for an edit on text `holder` holds: what holds it, then
/// accept, reject and a comment, each a fragment the caller can paste.
///
/// Another author's revision names what accepting or rejecting erases.
/// With the guard on, those two routes are left out: a deletion offers
/// restore, an insertion offers strike where the syntax has it, and a
/// move or a formatting change says plainly that settling would erase it.
pub(super) fn settle_hint(holder: &Holder<'_>, syntax: PlanSyntax) -> String {
    let mut lines = vec![format!("{}.", named(holder))];
    let foreign = holder.author != holder.actor;
    let guard = holder.keep_others && foreign;
    let noun = holder.held.noun();
    let [accept, reject] = holder.held.settles();
    let mut routes: Vec<(String, String, Option<&str>)> = Vec::new();
    if guard {
        if holder.held == Held::Inserted {
            if let Some(quote) = strike(syntax, holder) {
                routes.push((
                    "strike it".to_string(),
                    quote,
                    Some("their insertion stays, your deletion shows"),
                ));
            }
        } else if let Some(quote) = restore(syntax, holder) {
            routes.push((
                "put it back visibly".to_string(),
                quote,
                Some("their deletion stays, your insertion shows"),
            ));
        }
    } else {
        // Guard off, an insertion still offers the keeping move first,
        // where this syntax can spell a strike. Accept and reject stay,
        // and say what each one erases.
        if holder.held == Held::Inserted
            && foreign
            && let Some(quote) = strike(syntax, holder)
        {
            routes.push((
                "strike it".to_string(),
                quote,
                Some("their insertion stays, your deletion shows"),
            ));
        }
        if let Some(quote) = restore(syntax, holder) {
            routes.push((
                "put it back visibly".to_string(),
                quote,
                Some("their deletion stays, your insertion shows"),
            ));
        }
        routes.push((
            route_name(accept.0, holder, noun),
            settle(syntax, "accept", holder),
            Some(accept.1),
        ));
        routes.push((
            route_name(reject.0, holder, noun),
            settle(syntax, "reject", holder),
            Some(reject.1),
        ));
    }
    // No restore and no strike: say so, without a colon, so it is not a route.
    let bare = guard && routes.is_empty();
    routes.push((
        "or comment on it".to_string(),
        comment(syntax, holder.paragraph),
        None,
    ));
    let width = routes.iter().map(|r| r.0.len()).max().unwrap_or(0) + 1;
    let fragment = routes
        .iter()
        .filter(|r| r.2.is_some())
        .map(|r| r.1.chars().count())
        .max()
        .unwrap_or(0);
    if bare {
        lines.push("  accepting or rejecting would erase their change.".to_string());
    }
    for (name, quote, cost) in routes {
        let name = format!("{name}:");
        lines.push(match cost {
            Some(cost) => {
                let pad = " ".repeat(fragment - quote.chars().count());
                format!("  {name:<width$} {quote}{pad} ({cost})")
            }
            None => format!("  {name:<width$} {quote}"),
        });
    }
    lines.join("\n")
}

/// `base` as the route's name. Another author's revision says whose
/// markup accepting or rejecting erases; your own keeps `base`.
fn route_name(base: &str, holder: &Holder<'_>, noun: &str) -> String {
    if holder.author == holder.actor {
        base.to_string()
    } else {
        format!(r#"{base} (erases {:?}'s {noun})"#, holder.author)
    }
}

/// The refusal of an edit inside a deletion the same command restores:
/// the restore lands first, and the edit goes in a later command.
pub(super) fn restored_here_hint(holder: &Holder<'_>) -> String {
    format!(
        "{}, which this command restores: edit the restored words in a command of their own, after the restore.",
        named(holder)
    )
}

/// The lead with the revision named: its id, text, what it did, by whom.
fn named(holder: &Holder<'_>) -> String {
    let text = if holder.text.is_empty() {
        String::new()
    } else {
        format!("{} ", quoted(holder.text))
    };
    format!(
        "{} {}, {text}{} by {:?}",
        holder.lead,
        holder.id,
        holder.held.verb(),
        holder.author
    )
}

/// The target a v2 comment route names until [`super::v2_apply`] writes in
/// the refused operation's own: valid JSON, left to fill in like `find`.
pub(super) const OPERATION_TARGET: &str = r#"{"short_id":"…","long_id":"…"}"#;

/// `text` as a JSON string, quotes and backslashes escaped.
fn json(text: &str) -> String {
    serde_json::Value::from(text).to_string()
}

/// The strike of an insertion, as `syntax` spells it. The typed commands
/// have no strike yet.
fn strike(syntax: PlanSyntax, holder: &Holder<'_>) -> Option<String> {
    if holder.held != Held::Inserted {
        return None;
    }
    match syntax {
        PlanSyntax::V1 => Some(format!(
            r#"{{"kind":"strike","revision":{}}}"#,
            json(holder.id)
        )),
        PlanSyntax::Flags => Some(format!("-p {} --strike", shell_word(holder.id))),
        PlanSyntax::V2 => Some(format!(
            r#"{{"kind":"strike","target":{{"short_id":{},"long_id":{}}}}}"#,
            json(holder.id),
            json(holder.long_id)
        )),
        PlanSyntax::Typed => None,
    }
}

/// The restore of the revision, as `syntax` spells it: offered for a
/// deletion with words restore takes, in a syntax that has it.
fn restore(syntax: PlanSyntax, holder: &Holder<'_>) -> Option<String> {
    if holder.held != Held::Deleted || !holder.restorable || holder.text.is_empty() {
        return None;
    }
    match syntax {
        PlanSyntax::V1 => Some(format!(
            r#"{{"kind":"restore","revision":{}}}"#,
            json(holder.id)
        )),
        PlanSyntax::Flags => Some(format!("-p {} --restore", shell_word(holder.id))),
        PlanSyntax::V2 => Some(format!(
            r#"{{"kind":"restore","target":{{"short_id":{},"long_id":{}}}}}"#,
            json(holder.id),
            json(holder.long_id)
        )),
        // The typed commands have no restore yet.
        PlanSyntax::Typed => None,
    }
}

/// `id` as one shell word. A short id prints bare; a colon id carries the
/// document's `w:id` verbatim (`body:rev:1;x`), so it is single-quoted when
/// a shell would read anything in it.
fn shell_word(id: &str) -> std::borrow::Cow<'_, str> {
    let bare = !id.is_empty()
        && !id.starts_with(['#', '=', '~', '-'])
        && id
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b"._%:+-".contains(&b));
    if bare {
        id.into()
    } else {
        format!("'{}'", id.replace('\'', r"'\''")).into()
    }
}

/// `verb` (`accept` or `reject`) of the revision, as `syntax` spells it.
fn settle(syntax: PlanSyntax, verb: &str, holder: &Holder<'_>) -> String {
    settle_revision(syntax, verb, holder.id, holder.long_id)
}

fn settle_revision(syntax: PlanSyntax, verb: &str, id: &str, long_id: &str) -> String {
    match syntax {
        PlanSyntax::V1 => format!(
            r#""resolve_revisions":{{"{verb}":{{"ids":[{}]}}}}"#,
            json(id)
        ),
        PlanSyntax::Flags => format!("-p {} --{verb}", shell_word(id)),
        // Added to the refused command itself, which settles before it edits.
        PlanSyntax::Typed => format!("--{verb}-change {}", shell_word(id)),
        // A v2 plan's resolve_revisions names both lists.
        PlanSyntax::V2 => {
            let target = format!(
                r#"[{{"short_id":{},"long_id":{}}}]"#,
                json(id),
                json(long_id)
            );
            let (accept, reject) = if verb == "accept" {
                (target.as_str(), "[]")
            } else {
                ("[]", target.as_str())
            };
            format!(r#""resolve_revisions":{{"accept":{accept},"reject":{reject}}}"#)
        }
    }
}

/// A comment on the paragraph, as `syntax` spells it; a paragraph the
/// hint could not name is left to fill in.
fn comment(syntax: PlanSyntax, paragraph: &str) -> String {
    let paragraph = if paragraph.is_empty() {
        "…"
    } else {
        paragraph
    };
    match syntax {
        PlanSyntax::V1 => format!(
            r#"{{"kind":"comment","paragraph":{},"find":"…","text":"…"}}"#,
            json(paragraph)
        ),
        // The typed commands have no comment of their own; `add` is the
        // command line's.
        PlanSyntax::Flags | PlanSyntax::Typed => {
            format!(r#"add -p {paragraph} --anchor "…" --content "…""#)
        }
        PlanSyntax::V2 => {
            format!(r#"{{"kind":"comment","target":{OPERATION_TARGET},"find":"…","text":"…"}}"#)
        }
    }
}

/// `text` in quotes, cut to [`QUOTED`] characters with the cut said.
fn quoted(text: &str) -> String {
    if text.chars().count() <= QUOTED {
        return format!("{text:?}");
    }
    let head: String = text.chars().take(QUOTED).collect();
    format!("{head:?}…")
}

#[cfg(test)]
mod tests {
    use super::*;

    fn holder(held: Held) -> Holder<'static> {
        Holder {
            held,
            id: "r12",
            long_id: "document.w:del.w:id.12",
            author: "Bob Lee",
            actor: "Bob Lee",
            keep_others: false,
            text: "the bankers",
            paragraph: "p3",
            lead: "the text is inside",
            restorable: held == Held::Deleted,
        }
    }

    #[test]
    fn a_deletion_offers_restore_first_then_both_settles_then_comment() {
        assert_eq!(
            settle_hint(&holder(Held::Deleted), PlanSyntax::V1),
            [
                r#"the text is inside r12, "the bankers" deleted by "Bob Lee"."#,
                r#"  put it back visibly:  {"kind":"restore","revision":"r12"}            (their deletion stays, your insertion shows)"#,
                r#"  let it go:            "resolve_revisions":{"accept":{"ids":["r12"]}} (their words leave the document for good)"#,
                r#"  put it back silently: "resolve_revisions":{"reject":{"ids":["r12"]}} (their deletion disappears, no trace)"#,
                r#"  or comment on it:     {"kind":"comment","paragraph":"p3","find":"…","text":"…"}"#,
            ]
            .join("\n")
        );
    }

    /// A colon id carries the document's `w:id` verbatim (`body:rev:1;x`), so
    /// the command fragments quote it for the shell (review gid=54).
    #[test]
    fn a_colon_id_with_shell_syntax_is_quoted_in_command_fragments() {
        let mut odd = holder(Held::Deleted);
        odd.id = "body:rev:1;touch x";
        let flags = settle_hint(&odd, PlanSyntax::Flags);
        assert!(
            flags.contains("-p 'body:rev:1;touch x' --restore"),
            "{flags}"
        );
        assert!(
            flags.contains("-p 'body:rev:1;touch x' --accept"),
            "{flags}"
        );
        assert!(
            flags.contains("-p 'body:rev:1;touch x' --reject"),
            "{flags}"
        );
        let typed = settle_hint(&odd, PlanSyntax::Typed);
        assert!(
            typed.contains("--accept-change 'body:rev:1;touch x'"),
            "{typed}"
        );
        odd.id = "body:rev:it's";
        let flags = settle_hint(&odd, PlanSyntax::Flags);
        assert!(
            flags.contains(r#"-p 'body:rev:it'\''s' --accept"#),
            "{flags}"
        );
        // A shell-safe id prints bare, as before.
        assert!(settle_hint(&holder(Held::Deleted), PlanSyntax::Flags).contains("-p r12 --accept"));
    }

    #[test]
    fn each_syntax_quotes_its_own_fragments() {
        for syntax in PlanSyntax::ALL {
            let hint = settle_hint(&holder(Held::Deleted), syntax);
            let (wanted, foreign): (&[&str], &[&str]) = match syntax {
                PlanSyntax::V1 => (
                    &[
                        r#"{"ids":["r12"]}"#,
                        r#""paragraph":"p3""#,
                        r#"{"kind":"restore","revision":"r12"}"#,
                    ],
                    &["--accept", "short_id"],
                ),
                PlanSyntax::Flags => (
                    &[
                        "-p r12 --restore",
                        "-p r12 --accept",
                        "-p r12 --reject",
                        "add -p p3 --anchor",
                    ],
                    &["resolve_revisions"],
                ),
                PlanSyntax::V2 => (
                    &[
                        r#""accept":[{"short_id":"r12","long_id":"document.w:del.w:id.12"}]"#,
                        r#""target":"#,
                        r#"{"kind":"restore","target":{"short_id":"r12","long_id":"document.w:del.w:id.12"}}"#,
                    ],
                    &[r#""ids""#, "--accept", r#""paragraph""#],
                ),
                PlanSyntax::Typed => (
                    &[
                        "--accept-change r12",
                        "--reject-change r12",
                        "add -p p3 --anchor",
                    ],
                    &["resolve_revisions", "-p r12"],
                ),
            };
            for want in wanted {
                assert!(hint.contains(want), "{syntax:?} lacks {want}: {hint}");
            }
            for not in foreign {
                assert!(!hint.contains(not), "{syntax:?} quotes {not}: {hint}");
            }
        }
    }

    #[test]
    fn every_kind_names_what_the_revision_did() {
        for (held, says, first) in [
            (Held::Inserted, "inserted by", "keep it:"),
            (Held::Deleted, "deleted by", "put it back visibly:"),
            (Held::MovedHere, "moved here by", "keep the move:"),
            (Held::MovedAway, "moved away by", "keep the move:"),
            (Held::Formatted, "reformatted by", "keep their formatting:"),
        ] {
            let hint = settle_hint(&holder(held), PlanSyntax::V1);
            assert!(hint.lines().next().unwrap().contains(says), "{hint}");
            assert!(
                hint.lines().nth(1).unwrap().trim_start().starts_with(first),
                "{hint}"
            );
            assert!(!hint.contains("settle it first"), "{hint}");
        }
    }

    #[test]
    fn a_deletion_restore_cannot_take_offers_no_visible_route() {
        let hint = settle_hint(
            &Holder {
                restorable: false,
                ..holder(Held::Deleted)
            },
            PlanSyntax::V1,
        );
        assert_eq!(hint.lines().count(), 4, "{hint}");
        assert!(!hint.contains("restore"), "{hint}");
    }

    #[test]
    fn the_restore_route_parses_whatever_the_id_holds() {
        let odd = Holder {
            id: r#"r"1\2"#,
            ..holder(Held::Deleted)
        };
        let hint = settle_hint(&odd, PlanSyntax::V1);
        let line = hint.lines().nth(1).unwrap();
        let route: serde_json::Value = serde_json::from_str(fragment(line))
            .unwrap_or_else(|e| panic!("not JSON ({e}): {hint}"));
        assert_eq!(
            route,
            serde_json::json!({"kind":"restore","revision": odd.id})
        );
    }

    #[test]
    fn a_mark_without_text_is_named_without_quotes() {
        let hint = settle_hint(
            &Holder {
                text: "",
                lead: "that mark is",
                ..holder(Held::Inserted)
            },
            PlanSyntax::V1,
        );
        assert_eq!(
            hint.lines().next().unwrap(),
            r#"that mark is r12, inserted by "Bob Lee"."#
        );
    }

    /// A route line's fragment: what follows its label, without the cost.
    fn fragment(line: &str) -> &str {
        let rest = line.split_once(':').map_or(line, |(_, r)| r).trim_start();
        rest.rsplit_once(" (").map_or(rest, |(f, _)| f.trim_end())
    }

    /// The route lines of `hint` as JSON: accept, reject, comment (the
    /// last three, after any visible route).
    fn routes(hint: &str) -> [serde_json::Value; 3] {
        let all: Vec<&str> = hint.lines().collect();
        let lines = &all[all.len() - 4..];
        let parse = |s: String| {
            serde_json::from_str(&s).unwrap_or_else(|e| panic!("{s} is not JSON ({e}): {hint}"))
        };
        [
            parse(format!("{{{}}}", fragment(lines[1]))),
            parse(format!("{{{}}}", fragment(lines[2]))),
            parse(fragment(lines[3]).to_string()),
        ]
    }

    #[test]
    fn every_json_route_parses_whatever_the_ids_hold() {
        let odd = Holder {
            id: r#"r"1\2"#,
            long_id: r#"document.w:del.w:id."1\2"#,
            paragraph: r#"p"3\"#,
            ..holder(Held::Deleted)
        };
        let [accept, reject, comment] = routes(&settle_hint(&odd, PlanSyntax::V1));
        assert_eq!(accept["resolve_revisions"]["accept"]["ids"][0], odd.id);
        assert_eq!(reject["resolve_revisions"]["reject"]["ids"][0], odd.id);
        assert_eq!(comment["paragraph"], odd.paragraph);
        let [accept, reject, comment] = routes(&settle_hint(&odd, PlanSyntax::V2));
        let target = serde_json::json!({"short_id": odd.id, "long_id": odd.long_id});
        assert_eq!(accept["resolve_revisions"]["accept"][0], target);
        assert_eq!(reject["resolve_revisions"]["reject"][0], target);
        assert_eq!(comment["kind"], "comment");
    }

    #[test]
    fn v2_routes_parse_as_the_plan_v2_types() {
        let hint = settle_hint(&holder(Held::Deleted), PlanSyntax::V2);
        let [accept, reject, comment] = routes(&hint);
        for route in [accept, reject] {
            serde_json::from_value::<super::super::v2::RevisionDecisions>(
                route["resolve_revisions"].clone(),
            )
            .unwrap_or_else(|e| panic!("{route} is no resolve_revisions ({e}): {hint}"));
        }
        serde_json::from_value::<super::super::v2::Operation>(comment.clone())
            .unwrap_or_else(|e| panic!("{comment} is no operation ({e}): {hint}"));
    }

    #[test]
    fn a_paragraph_the_hint_cannot_name_is_left_to_fill_in() {
        let lost = Holder {
            paragraph: "",
            ..holder(Held::Deleted)
        };
        let v1 = settle_hint(&lost, PlanSyntax::V1);
        let [.., comment] = routes(&v1);
        assert_eq!(comment["paragraph"], "…", "{v1}");
        let flags = settle_hint(&lost, PlanSyntax::Flags);
        assert!(
            flags
                .lines()
                .last()
                .unwrap()
                .ends_with(r#"add -p … --anchor "…" --content "…""#),
            "{flags}"
        );
    }

    #[test]
    fn a_long_revision_is_quoted_with_the_cut_said() {
        let text = "x".repeat(QUOTED + 5);
        let hint = settle_hint(
            &Holder {
                text: &text,
                ..holder(Held::Deleted)
            },
            PlanSyntax::V1,
        );
        assert!(
            hint.contains(&format!("\"{}\"…", "x".repeat(QUOTED))),
            "{hint}"
        );
    }

    /// Another author's revision: the plan author is not Bob Lee.
    fn foreign(held: Held) -> Holder<'static> {
        Holder {
            author: "Trainer 1 - AgentCo",
            actor: "Jubarte",
            keep_others: false,
            ..holder(held)
        }
    }

    #[test]
    fn hint_names_the_cost_of_erasing_another_authors_deletion_in_every_syntax() {
        for syntax in PlanSyntax::ALL {
            let hint = settle_hint(&foreign(Held::Deleted), syntax);
            assert!(
                hint.contains(r#"let it go (erases "Trainer 1 - AgentCo"'s deletion):"#),
                "{syntax:?}\n{hint}"
            );
            assert!(
                hint.contains(r#"put it back silently (erases "Trainer 1 - AgentCo"'s deletion):"#),
                "{syntax:?}\n{hint}"
            );
        }
    }

    #[test]
    fn hint_names_the_cost_of_erasing_another_authors_insertion_move_and_formatting() {
        for (held, first, noun) in [
            (Held::Inserted, "keep it", "insertion"),
            (Held::MovedHere, "keep the move", "move"),
            (Held::MovedAway, "undo it silently", "move"),
            (Held::Formatted, "keep their formatting", "formatting"),
        ] {
            let hint = settle_hint(&foreign(held), PlanSyntax::V1);
            let label = format!(r#"{first} (erases "Trainer 1 - AgentCo"'s {noun}):"#);
            assert!(hint.contains(&label), "{hint}");
        }
    }

    #[test]
    fn hint_guard_on_drops_accept_and_reject_for_another_author_in_every_syntax() {
        for syntax in PlanSyntax::ALL {
            let guarded = Holder {
                keep_others: true,
                ..foreign(Held::Deleted)
            };
            let hint = settle_hint(&guarded, syntax);
            assert!(
                !hint.contains("--accept")
                    && !hint.contains("\"accept\"")
                    && !hint.contains("--reject")
                    && !hint.contains("\"reject\"")
                    && !hint.contains("--accept-change")
                    && !hint.contains("--reject-change"),
                "{syntax:?}\n{hint}"
            );
            match syntax {
                PlanSyntax::V1 | PlanSyntax::Flags | PlanSyntax::V2 => {
                    assert!(hint.contains("restore"), "{syntax:?}\n{hint}");
                }
                PlanSyntax::Typed => {
                    assert!(
                        hint.contains("accepting or rejecting would erase their change"),
                        "{syntax:?}\n{hint}"
                    );
                    assert!(!hint.contains("restore"), "{syntax:?}\n{hint}");
                }
            }
        }
    }

    #[test]
    fn hint_guard_off_offers_strike_first_for_another_authors_insertion() {
        for syntax in [PlanSyntax::V1, PlanSyntax::Flags, PlanSyntax::V2] {
            let hint = settle_hint(&foreign(Held::Inserted), syntax);
            let routes: Vec<&str> = hint.lines().skip(1).collect();
            assert!(
                routes[0].contains("strike it")
                    && routes[0].contains("their insertion stays, your deletion shows"),
                "{syntax:?}\n{hint}"
            );
            assert!(
                hint.contains(r#"keep it (erases "Trainer 1 - AgentCo"'s insertion):"#),
                "{syntax:?}\n{hint}"
            );
            assert!(
                hint.contains(
                    r#"take it out silently (erases "Trainer 1 - AgentCo"'s insertion):"#
                ),
                "{syntax:?}\n{hint}"
            );
        }
        let typed = settle_hint(&foreign(Held::Inserted), PlanSyntax::Typed);
        assert!(!typed.lines().nth(1).unwrap().contains("strike"), "{typed}");
        assert!(
            typed.contains(r#"keep it (erases "Trainer 1 - AgentCo"'s insertion):"#),
            "{typed}"
        );
        let own = settle_hint(&holder(Held::Inserted), PlanSyntax::V1);
        assert!(!own.contains("strike"), "{own}");
    }

    #[test]
    fn hint_guard_on_strikes_an_insertion_where_the_syntax_has_strike() {
        let guarded = Holder {
            keep_others: true,
            ..foreign(Held::Inserted)
        };
        let v1 = settle_hint(&guarded, PlanSyntax::V1);
        assert!(v1.contains(r#"{"kind":"strike","revision":"r12"}"#), "{v1}");
        assert!(!v1.contains("resolve_revisions"), "{v1}");
        let flags = settle_hint(&guarded, PlanSyntax::Flags);
        assert!(flags.contains("-p r12 --strike"), "{flags}");
        assert!(
            !flags.contains("--accept") && !flags.contains("--reject"),
            "{flags}"
        );
        let v2 = settle_hint(&guarded, PlanSyntax::V2);
        assert!(
            v2.contains(
                r#"{"kind":"strike","target":{"short_id":"r12","long_id":"document.w:del.w:id.12"}}"#
            ),
            "{v2}"
        );
        assert!(!v2.contains("resolve_revisions"), "{v2}");
        let typed = settle_hint(&guarded, PlanSyntax::Typed);
        assert!(
            typed.contains("accepting or rejecting would erase their change"),
            "{typed}"
        );
        assert!(!typed.contains("strike"), "{typed}");
        assert!(!typed.contains("resolve_revisions"), "{typed}");
    }

    #[test]
    fn hint_guard_on_offers_only_a_comment_for_another_authors_move() {
        let guarded = Holder {
            keep_others: true,
            ..foreign(Held::MovedHere)
        };
        for syntax in PlanSyntax::ALL {
            let hint = settle_hint(&guarded, syntax);
            assert!(
                hint.contains("accepting or rejecting would erase their change"),
                "{syntax:?}\n{hint}"
            );
            assert!(
                !hint.contains("resolve_revisions")
                    && !hint.contains("--accept")
                    && !hint.contains("--reject-change"),
                "{syntax:?}\n{hint}"
            );
        }
    }

    #[test]
    fn hint_guard_on_keeps_the_four_routes_for_your_own_deletion() {
        let own = Holder {
            keep_others: true,
            ..holder(Held::Deleted)
        };
        let hint = settle_hint(&own, PlanSyntax::V1);
        assert!(hint.contains("  let it go:"), "{hint}");
        assert!(hint.contains("  put it back silently:"), "{hint}");
        assert!(!hint.contains("erases"), "{hint}");
    }
}

#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod holder_branch_tests {
    use super::*;

    #[test]
    fn flags_list_each_occurrence_with_cut_marks_on_long_sides() {
        let text = "x long words before the anchor here and then many more words after anchor";
        let hits: Vec<(usize, usize)> = text
            .match_indices("anchor")
            .map(|(s, a)| (s, s + a.len()))
            .collect();
        let message = PlanSyntax::Flags.ambiguous_anchor(text, "anchor", &hits);
        assert!(message.contains("occurs 2 times"), "{message}");
        assert!(message.contains("--occurrence 1..=2"), "{message}");
        let lines: Vec<&str> = message.lines().filter(|l| l.starts_with("  ")).collect();
        assert_eq!(lines.len(), 2, "{message}");
        // The first hit has over 20 chars on both sides, the last none after.
        assert!(lines[0].contains('…'), "{message}");
        assert!(!lines[1].trim_end().ends_with("…\""), "{message}");
        let near = PlanSyntax::Flags.ambiguous_anchor("ab x ab", "ab", &[(0, 2), (5, 7)]);
        assert!(!near.contains('…'), "{near}");
        let short = PlanSyntax::V1.ambiguous_anchor("ab ab", "ab", &[(0, 2), (3, 5)]);
        assert!(short.contains("\"occurrence\" to 1..=2"), "{short}");
        assert!(!short.contains("\n  1:"), "{short}");
    }

    fn paragraph(xml: &str) -> (Dom, NodeId) {
        let mut dom = Dom::new();
        let doc = dom.parse_xdocument(&format!(r#"<w:p xmlns:w="{}">{xml}</w:p>"#, W::URI));
        let p = dom.root(doc).unwrap();
        (dom, p)
    }

    #[test]
    fn removed_holder_finds_the_deletion_an_anchor_reaches_into() {
        let (dom, p) = paragraph(
            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>"#,
        );
        let del = dom.descendants(p, Some(&W::del()))[0];
        assert_eq!(removed_holder(&dom, p, "gone words"), Some(del));
        assert_eq!(removed_holder(&dom, p, "{--gone--}"), Some(del));
        assert_eq!(
            removed_holder(&dom, p, "\n\u{2011}\u{ad}\u{fffc}gone"),
            Some(del)
        );
        assert_eq!(removed_holder(&dom, p, "Keep"), None);
        assert_eq!(removed_holder(&dom, p, "boxed"), None);
        assert_eq!(removed_holder(&dom, p, ""), None);
    }

    fn holder<'a>(held: Held, restorable: bool, text: &'a str) -> Holder<'a> {
        Holder {
            held,
            id: "r3",
            long_id: "body:rev:3",
            author: "Bo",
            actor: "Ed",
            keep_others: true,
            text,
            paragraph: "p0",
            lead: "the text is inside",
            restorable,
        }
    }

    #[test]
    fn strike_and_restore_fragments_follow_the_kind_and_syntax() {
        let ins = holder(Held::Inserted, false, "new");
        let del = holder(Held::Deleted, true, "old");
        for syntax in PlanSyntax::ALL {
            let has = syntax != PlanSyntax::Typed;
            assert_eq!(strike(syntax, &ins).is_some(), has, "{syntax:?}");
            assert_eq!(restore(syntax, &del).is_some(), has, "{syntax:?}");
            assert_eq!(strike(syntax, &del), None);
            assert_eq!(restore(syntax, &ins), None);
            assert_eq!(restore(syntax, &holder(Held::Deleted, false, "old")), None);
            assert_eq!(restore(syntax, &holder(Held::Deleted, true, "")), None);
        }
        assert_eq!(strike(PlanSyntax::Flags, &ins).unwrap(), "-p r3 --strike");
        assert_eq!(shell_word(""), "''");
        assert_eq!(shell_word("#x"), "'#x'");
        assert_eq!(shell_word("a b"), "'a b'");
        assert_eq!(shell_word("it's"), r"'it'\''s'");
        assert_eq!(shell_word("body:rev:1"), "body:rev:1");
    }
}