Skip to main content

jubarte_edit/edit/
anchor_error.rs

1// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! Actionable refusals for v2 literal anchors (V2-11).
6//!
7//! [`v2_resolve`] and [`v2_resolve_all`] select exactly like
8//! [`super::v2_select`] and [`super::v2_select_all`] — every exact start
9//! position counted, overlapping candidates included — and, when the anchor
10//! misses or repeats, return a structured [`crate::result::Error`] instead of
11//! a bare message: the stable code, the operation pointer, the source digest,
12//! the requested target, the complete match count, bounded exact context and
13//! a read continuation as a structured argv.
14//!
15//! The refusal's facts all come from one open of the source ([`snapshot`]):
16//! existence, the target's own text, the elsewhere suggestions and the
17//! missing-target counts agree because they are one parse, on every path,
18//! including the ones that resolve. The working text is bound to the target
19//! by [`Working`]: a caller with no settled text passes [`Working::InSource`]
20//! and the resolver derives the text itself, while a caller holding a settled
21//! working document W (V2-06/V2-10) states that provenance with
22//! [`Working::Settled`].
23//!
24//! A target is whatever `-p` accepts ([`crate::ids::parse_location`]): a
25//! paragraph (`p12`), a story or its paragraph (`header1`, `header1.p2`), a
26//! table cell (`t0.row1.cell2`, its own paragraph), a comment (`c5`), the
27//! text a comment covers (`c5.text`) or a revision (`r12`). A target the
28//! source does not have refuses `ANCHOR_NOT_FOUND` before anything else is
29//! judged — an empty anchor or an occurrence 0 included — and its message
30//! says what the source does have: the story's own paragraph count when the
31//! target names a story, the body's, or the table, comment or revision
32//! counts. A source that cannot be parsed says so; it never claims counts it
33//! could not see.
34//!
35//! Candidate matches in other paragraphs are suggestions only: they appear in
36//! the message and as read continuations, never as an automatic retarget, and
37//! the refused error keeps naming the requested target. Document text stays
38//! untrusted data: it is echoed bounded (and escaped, in messages) and never
39//! lands in an argv. The caller's anchor is bounded the same way: a pasted
40//! clause shows its first `WINDOW` characters, with the cut said.
41//!
42//! Bounds: a match shows up to `WINDOW` characters on either side (a miss
43//! shows the first `WINDOW` characters of the actual target text); at most
44//! `MAX_SUGGESTED_TARGETS` other paragraphs are suggested.
45
46use super::EditError;
47use super::anchor::{shown, v2_candidates, v2_select, v2_select_all};
48use crate::comments::CommentRecord;
49use crate::ids::{
50    Location, ShortId, Step, Story, paragraph_place, parse_change_ids, parse_location,
51};
52use crate::inspect::{InspectError, Paragraph, Snapshot, snapshot, source_sha256};
53use crate::result::{CommitState, Context, Error, NextAction};
54
55/// Characters of context on either side of a match, of the actual target
56/// text shown on a miss, and of the anchor the message quotes.
57const WINDOW: usize = 20;
58/// Other paragraphs a refusal may suggest at most.
59const MAX_SUGGESTED_TARGETS: usize = 5;
60/// Blocks the read continuation of a missing target suggests.
61const READ_SUGGESTION_HEAD: usize = 20;
62
63/// The refused request's own facts: which operation asked, which target it
64/// named, the anchor it sent, and where the source lives for read
65/// continuations. None of this is document text.
66#[derive(Clone, Copy, Debug)]
67pub struct AnchorRefusal<'a> {
68    /// Operation pointer or ID (`/operations/3`, an op id, ...).
69    pub operation: Option<&'a str>,
70    /// The requested target (`p15`, `header1.p3`, ...), kept verbatim: the
71    /// refusal never retargets.
72    pub target: &'a str,
73    /// The exact literal anchor that missed or repeated.
74    pub anchor: &'a str,
75    /// Source path for read continuations. The digest always binds the
76    /// bytes; without a path the argv omits the file and says so.
77    pub path: Option<&'a str>,
78}
79
80impl<'a> AnchorRefusal<'a> {
81    /// The refusal facts for one operation.
82    pub fn new(target: &'a str, anchor: &'a str) -> Self {
83        Self {
84            operation: None,
85            target,
86            anchor,
87            path: None,
88        }
89    }
90
91    /// Set the operation pointer.
92    #[must_use]
93    pub fn with_operation(mut self, operation: &'a str) -> Self {
94        self.operation = Some(operation);
95        self
96    }
97
98    /// Set the source path for read continuations.
99    #[must_use]
100    pub fn with_path(mut self, path: &'a str) -> Self {
101        self.path = Some(path);
102        self
103    }
104}
105
106/// Where an anchor's working text comes from, so the refusal's facts cannot
107/// drift away from the target they attest.
108#[derive(Clone, Copy, Debug)]
109pub enum Working<'a> {
110    /// The target's own text in the original source. The resolver reads it
111    /// from the one open it already makes, so a caller with no settled text
112    /// cannot hand in text that is not the target's.
113    InSource,
114    /// The target's text in the settled working document W (V2-06/V2-10).
115    /// Settlement is the caller's: the refusal still binds the digest, the
116    /// target inventory and the elsewhere suggestions to `source`, and this
117    /// variant is where the caller states that the text is W's, not S's.
118    Settled(&'a str),
119}
120
121/// Select the unique v2 literal candidate (or the 1-based `occurrence`)
122/// exactly like [`super::v2_select`], refusing with a structured, actionable
123/// error when the anchor misses, repeats or is invalid.
124///
125/// `working` binds the target's text to where it came from
126/// ([`Working`]); `source` is the original package the request is bound to
127/// (its digest, its target inventory and its elsewhere suggestions), opened
128/// once for all of them. A request against a target the source does not have
129/// refuses before any text is searched — whatever else is wrong with it —
130/// because there is nothing to edit, and no match elsewhere retargets it.
131///
132/// # Errors
133///
134/// [`Error`] (boxed to keep the [`Result`] small) with the code
135/// [`super::v2_select`] chose (`INVALID_EDIT`, `ANCHOR_NOT_FOUND`,
136/// `AMBIGUOUS_ANCHOR`), `ANCHOR_NOT_FOUND` for a missing target, or the
137/// open failure's code for a source that cannot be read, carrying the
138/// bounded context and read continuations described in the module docs.
139pub fn v2_resolve(
140    source: &[u8],
141    working: Working<'_>,
142    refusal: &AnchorRefusal<'_>,
143    occurrence: Option<usize>,
144) -> Result<(usize, usize), Box<Error>> {
145    let snap = open(source, refusal)?;
146    let target = find_target(&snap, refusal.target);
147    let text = match (target, working) {
148        (Target::Missing, _) => return Err(Box::new(missing_target(&snap, refusal))),
149        (Target::SeveralChanges, _) => {
150            return Err(Box::new(several_changes(&snap, refusal)));
151        }
152        (Target::Here(text), Working::InSource) => text,
153        (Target::Here(_), Working::Settled(text)) => text,
154    };
155    let skip = skip_id(&snap, refusal.target);
156    match v2_select(text, refusal.anchor, occurrence) {
157        Ok(range) => Ok(range),
158        Err(edit) => Err(Box::new(refused(
159            &snap, text, &skip, refusal, &edit, occurrence, None,
160        ))),
161    }
162}
163
164/// Select every exact v2 candidate exactly like [`super::v2_select_all`],
165/// requiring the complete count to equal `expected` and disjoint ranges,
166/// refusing with a structured, actionable error otherwise.
167///
168/// # Errors
169///
170/// [`Error`] (boxed to keep the [`Result`] small) with the code
171/// [`super::v2_select_all`] chose (`INVALID_EDIT`, `ANCHOR_NOT_FOUND`,
172/// `AMBIGUOUS_ANCHOR`, `OVERLAPPING_EDITS`), `ANCHOR_NOT_FOUND` for a
173/// missing target, or the open failure's code for a source that cannot be
174/// read, carrying the bounded context and read continuations described in
175/// the module docs.
176pub fn v2_resolve_all(
177    source: &[u8],
178    working: Working<'_>,
179    refusal: &AnchorRefusal<'_>,
180    expected: usize,
181) -> Result<Vec<(usize, usize)>, Box<Error>> {
182    let snap = open(source, refusal)?;
183    let target = find_target(&snap, refusal.target);
184    let text = match (target, working) {
185        (Target::Missing, _) => return Err(Box::new(missing_target(&snap, refusal))),
186        (Target::SeveralChanges, _) => {
187            return Err(Box::new(several_changes(&snap, refusal)));
188        }
189        (Target::Here(text), Working::InSource) => text,
190        (Target::Here(_), Working::Settled(text)) => text,
191    };
192    let skip = skip_id(&snap, refusal.target);
193    match v2_select_all(text, refusal.anchor, expected) {
194        Ok(ranges) => Ok(ranges),
195        Err(edit) => Err(Box::new(refused(
196            &snap,
197            text,
198            &skip,
199            refusal,
200            &edit,
201            None,
202            Some(expected),
203        ))),
204    }
205}
206
207/// Validate a declared story using the same missing-target refusal as anchors.
208/// Its only caller is the CLI's typed actions (`edit::inline`).
209#[doc(hidden)]
210pub fn require_story(source: &[u8], story: &str) -> Result<(), Box<Error>> {
211    let refusal = AnchorRefusal::new(story, "").with_operation("/operations/0");
212    let snap = open(source, &refusal)?;
213    if story == "body" || snap.stories.iter().any(|s| s.id == story) {
214        return Ok(());
215    }
216    let mut error = missing_target(&snap, &refusal);
217    let available = std::iter::once("body")
218        .chain(snap.stories.iter().map(|s| s.id.as_str()))
219        .collect::<Vec<_>>()
220        .join(", ");
221    error.message = format!("unknown story {story:?}; the source has stories: {available}");
222    Err(Box::new(error))
223}
224
225/// The one open every path through the resolver shares, as [`snapshot`]
226/// serves every field: the source's paragraphs, stories, tables, changes and
227/// comments, or the structured refusal that says it could not be read. A
228/// source that fails here is never described by counts.
229fn open(source: &[u8], refusal: &AnchorRefusal<'_>) -> Result<Snapshot, Box<Error>> {
230    snapshot(source).map_err(|error| {
231        let code = match &error {
232            InspectError::Admission(refused) => refused.code(),
233            _ => "INVALID_DOCUMENT",
234        };
235        Box::new(
236            base(&source_sha256(source), refusal, code).with_message(format!(
237                "the source could not be read ({error}); no anchor was searched"
238            )),
239        )
240    })
241}
242
243/// What one request's target is, as the source's own inventory holds it.
244enum Target<'s> {
245    /// The target exists, and this is its own text in the source.
246    Here(&'s str),
247    /// The target names several marks (`r1+2`): it exists, but no one
248    /// text carries an anchor.
249    SeveralChanges,
250    /// The source does not have the target.
251    Missing,
252}
253
254/// Find `target` in the snapshot: every spelling `-p` accepts
255/// ([`parse_location`]), or [`Target::Missing`].
256fn find_target<'s>(snap: &'s Snapshot, target: &str) -> Target<'s> {
257    match parse_location(target) {
258        Err(_) => Target::Missing,
259        Ok(Location::Paragraph(id)) => {
260            if let Some((story, n)) = paragraph_place(&id) {
261                let list: &[Paragraph] = if story == "body" {
262                    &snap.paragraphs
263                } else if let Some(found) = snap.stories.iter().find(|s| s.id == story) {
264                    &found.paragraphs
265                } else {
266                    return Target::Missing;
267                };
268                return match list.get(n) {
269                    Some(paragraph) => Target::Here(&paragraph.text),
270                    None => Target::Missing,
271                };
272            }
273            match cell_paragraph(snap, &id) {
274                Some((_, text)) => Target::Here(text),
275                None => Target::Missing,
276            }
277        }
278        Ok(Location::Comment(n)) => match comment(snap, n) {
279            Some(found) => Target::Here(&found.text),
280            None => Target::Missing,
281        },
282        Ok(Location::CommentText(n)) => match comment(snap, n) {
283            Some(found) => Target::Here(&found.anchor_text),
284            None => Target::Missing,
285        },
286        Ok(Location::Changes(ids)) => {
287            // Each id names one mark, as `list_changes` lists them: a
288            // change of one, or a mark of a change of several (`r2`, the
289            // inserted side of `r1+2`), with its own covered text.
290            let spelled: Vec<String> = ids.iter().map(|change| change.short()).collect();
291            let mark = |short: &str| {
292                snap.changes.iter().find_map(|change| {
293                    if change.members.is_empty() {
294                        (change.id == short).then_some(change.text.as_str())
295                    } else {
296                        change
297                            .members
298                            .iter()
299                            .find(|member| member.id == short)
300                            .map(|member| member.text.as_str())
301                    }
302                })
303            };
304            if !spelled.iter().all(|short| mark(short).is_some()) {
305                return Target::Missing;
306            }
307            match spelled.as_slice() {
308                [one] => mark(one).map_or(Target::Missing, Target::Here),
309                _ => Target::SeveralChanges,
310            }
311        }
312    }
313}
314
315/// The comment `w:id` `n` in the snapshot.
316fn comment(snap: &Snapshot, n: u32) -> Option<&CommentRecord> {
317    snap.comments.iter().find(|comment| comment.id == n)
318}
319
320/// The cell `tN.rowR.cellC[.pK]`: its first (or K-th) own paragraph, as the
321/// snapshot's grids hold it. Numbering follows the snapshot's table order; a
322/// snapshot numbers top-level tables as `edit -p` does. Nested tables
323/// remain outside this helper's supported cell-target grammar.
324fn cell_paragraph<'s>(snap: &'s Snapshot, id: &str) -> Option<(String, &'s str)> {
325    let Ok(ShortId::Block {
326        story: Story::Body,
327        path,
328    }) = id.parse::<ShortId>()
329    else {
330        return None;
331    };
332    let [Step::Table(t), Step::Row(row), Step::Cell(cell), rest @ ..] = path.as_slice() else {
333        return None;
334    };
335    let index = match rest {
336        [] => 0,
337        [Step::Paragraph(k)] => *k,
338        _ => return None,
339    };
340    let table = snap.tables.iter().find(|table| table.index == *t)?;
341    let held = table.rows.get(*row)?.get(*cell)?;
342    let short = held.paragraph_ids.get(index)?;
343    let (_, n) = paragraph_place(short)?;
344    let paragraph = snap.paragraphs.get(n)?;
345    Some((paragraph.id.clone(), &paragraph.text))
346}
347
348/// The paragraph a miss must not suggest back: the requested spelling for a
349/// paragraph target, the cell's own paragraph for a cell target, and the
350/// target itself otherwise.
351fn skip_id(snap: &Snapshot, target: &str) -> String {
352    if let Ok(Location::Paragraph(id)) = parse_location(target)
353        && paragraph_place(&id).is_none()
354        && let Some((paragraph, _)) = cell_paragraph(snap, &id)
355    {
356        return paragraph;
357    }
358    target.to_string()
359}
360
361/// The structured refusal for a target the source does not have: stable
362/// code, operation, digest, the requested target kept verbatim, zero
363/// matches, and a bounded read of what does exist.
364fn missing_target(snap: &Snapshot, refusal: &AnchorRefusal<'_>) -> Error {
365    let mut error = base(&snap.source_sha256, refusal, "ANCHOR_NOT_FOUND")
366        .with_matches(0)
367        .with_message(missing_target_message(snap, refusal.target));
368    error.push_next_action(read_head(refusal));
369    error
370}
371
372/// What a missing target's message says: the target, kept verbatim, and
373/// what the source does have where that orients the caller — the story's
374/// own paragraph count when the target names a story, the body's, the
375/// table, comment or revision counts, and the settled spelling of an
376/// expired id.
377fn missing_target_message(snap: &Snapshot, target: &str) -> String {
378    let body = format!(
379        "the body has {}",
380        plural(snap.summary.paragraphs, "paragraph")
381    );
382    match parse_location(target) {
383        Ok(Location::Comment(_)) | Ok(Location::CommentText(_)) => format!(
384            "no comment {target} in the source; the source has {}",
385            plural(snap.summary.comments, "comment")
386        ),
387        Ok(Location::Changes(_)) => format!(
388            "no revision {target} in the source; the source has {}",
389            plural(snap.summary.revisions, "change")
390        ),
391        Ok(Location::Paragraph(id)) => match paragraph_place(&id) {
392            Some((story, _)) if story != "body" => {
393                match snap.stories.iter().find(|s| s.id == story) {
394                    Some(found) => format!(
395                        "no paragraph {target} in the source; the story {story} has {}",
396                        plural(found.paragraphs.len(), "paragraph")
397                    ),
398                    None => format!(
399                        "no paragraph {target} in the source; the source has no {story} story; {body}"
400                    ),
401                }
402            }
403            Some(_) => format!("no paragraph {target} in the source; {body}"),
404            None => format!(
405                "no paragraph {target} in the source; the source has {}",
406                plural(snap.tables.len(), "table")
407            ),
408        },
409        Err(refused) => match &refused.hint {
410            Some(hint) => {
411                format!(
412                    "no paragraph {target} in the source; the settled spelling is {hint}; {body}"
413                )
414            }
415            None => format!("no paragraph {target} in the source; {body}"),
416        },
417    }
418}
419
420/// The structured refusal for a target that names several marks: it
421/// exists, but no one text carries an anchor.
422fn several_changes(snap: &Snapshot, refusal: &AnchorRefusal<'_>) -> Error {
423    let one_by_one: Vec<String> = parse_change_ids(refusal.target)
424        .map(|ids| ids.iter().map(|change| change.short()).collect())
425        .unwrap_or_default();
426    let spelled = match one_by_one.as_slice() {
427        [rest @ .., last] if rest.len() < 3 => format!("{} or {last}", rest.join(" or ")),
428        _ => String::new(),
429    };
430    let mut error = base(&snap.source_sha256, refusal, "INVALID_EDIT").with_message(format!(
431        "{} names {} marks; an anchor targets one{}",
432        refusal.target,
433        one_by_one.len(),
434        if spelled.is_empty() {
435            String::new()
436        } else {
437            format!(" ({spelled})")
438        }
439    ));
440    error.push_next_action(read_target(refusal));
441    error
442}
443
444/// The shared refusal skeleton: code, operation pointer, source digest,
445/// requested target, no-retry and no-commit.
446fn base(digest: &str, refusal: &AnchorRefusal<'_>, code: &str) -> Error {
447    let mut error = Error::new(code)
448        .with_source_digest(digest)
449        .with_target(refusal.target)
450        .with_retryable(false)
451        .with_commit_state(CommitState::NotCommitted);
452    if let Some(operation) = refusal.operation {
453        error = error.with_operation(operation);
454    }
455    error
456}
457
458/// Build the structured refusal for an anchor that missed or repeated in an
459/// existing target: the complete match count, bounded exact context, the
460/// paragraphs holding the anchor elsewhere (a miss only, suggestions only)
461/// and read continuations. `skip` is the paragraph not to suggest back.
462fn refused(
463    snap: &Snapshot,
464    working: &str,
465    skip: &str,
466    refusal: &AnchorRefusal<'_>,
467    edit: &EditError,
468    occurrence: Option<usize>,
469    expected: Option<usize>,
470) -> Error {
471    let mut error = base(&snap.source_sha256, refusal, &edit.code);
472    if edit.code == "INVALID_EDIT" {
473        error = error.with_message(edit.message.clone());
474        error.push_next_action(read_target(refusal));
475        return error;
476    }
477    let candidates = v2_candidates(working, refusal.anchor);
478    let count = candidates.len();
479    error = error.with_matches(count);
480    error.near = edit.near.as_deref().cloned();
481    let near_range = error
482        .near
483        .as_ref()
484        .and_then(|near| near.occurrences.first())
485        .map(|hit| (hit.offset, hit.offset + hit.text.len()));
486    error = error.with_context(match candidates.first().copied().or(near_range) {
487        Some((start, end)) => around(working, start, end),
488        None => Context::new(bounded_start(working), "", "")
489            .with_truncated(working.chars().count() > WINDOW),
490    });
491    let shown_anchor = quoted_anchor(refusal.anchor);
492    let mut message = match (count, occurrence, expected) {
493        (0, _, _) => format!(
494            "{shown_anchor} occurs 0 times in {}; {} starts {}",
495            refusal.target,
496            refusal.target,
497            shown(&bounded_start(working))
498        ),
499        // all-matches refusals never take an occurrence: name their own
500        // variant before the occurrence guidance below.
501        (_, _, _) if edit.code == "OVERLAPPING_EDITS" => format!(
502            "{shown_anchor} occurs {count} times in {} and those ranges overlap, so none of them is replaced",
503            refusal.target
504        ),
505        (_, _, Some(wanted)) => format!(
506            "{shown_anchor} occurs {count} times in {}, not the expected {wanted}",
507            refusal.target
508        ),
509        (_, None, _) => format!(
510            "{shown_anchor} occurs {count} times in {}; set \"occurrence\" to 1..={count}",
511            refusal.target
512        ),
513        (_, Some(k), _) if k > count => format!(
514            "{shown_anchor} occurs {count} times in {}; occurrence {k} is outside occurrence 1..={count}",
515            refusal.target
516        ),
517        // The one case left (an occurrence inside 1..=count, no expected
518        // count) is a selection v2_select resolves; spelling the arm keeps
519        // the match exhaustive, so a new refusal code cannot fall through
520        // to a wrong message silently.
521        (_, Some(_), None) => format!("{shown_anchor} occurs {count} times in {}", refusal.target),
522    };
523    error.push_next_action(read_target(refusal));
524    if count == 0 {
525        // A miss is where elsewhere helps: bounded suggestions, reads only.
526        let suggestions = suggestions_elsewhere(snap, skip, refusal.anchor);
527        if !suggestions.list.is_empty() {
528            message.push_str("; it occurs elsewhere: ");
529            message.push_str(
530                &suggestions
531                    .list
532                    .iter()
533                    .map(|(id, hits)| format!("{id} ({hits})"))
534                    .collect::<Vec<_>>()
535                    .join(", "),
536            );
537            if suggestions.more > 0 {
538                message.push_str(&format!(", … (+{} more paragraphs)", suggestions.more));
539            }
540            for (id, hits) in &suggestions.list {
541                error.push_next_action(suggest_read(refusal, id, *hits));
542            }
543        }
544    }
545    error.with_message(message)
546}
547
548/// Other paragraphs where the anchor occurs: `(id, complete count)` in
549/// document order (body, then stories), capped, plus how many more were
550/// cut, all from the one open the resolver already made.
551fn suggestions_elsewhere(snap: &Snapshot, skip: &str, anchor: &str) -> Suggestions {
552    let mut list = Vec::new();
553    let mut more = 0;
554    for paragraph in snap.paragraphs.iter().chain(
555        snap.stories
556            .iter()
557            .flat_map(|story| story.paragraphs.iter()),
558    ) {
559        if paragraph.id == skip {
560            continue;
561        }
562        let hits = v2_candidates(&paragraph.text, anchor).len();
563        if hits == 0 {
564            continue;
565        }
566        if list.len() == MAX_SUGGESTED_TARGETS {
567            more += 1;
568        } else {
569            list.push((paragraph.id.clone(), hits));
570        }
571    }
572    Suggestions { list, more }
573}
574
575/// Bounded elsewhere-candidate list.
576struct Suggestions {
577    /// The suggested paragraphs, at most `MAX_SUGGESTED_TARGETS`.
578    list: Vec<(String, usize)>,
579    /// Suggested paragraphs cut by the cap.
580    more: usize,
581}
582
583/// Up to `WINDOW` characters from the start of the actual target text.
584fn bounded_start(working: &str) -> String {
585    working.chars().take(WINDOW).collect()
586}
587
588/// The anchor as a message quotes it: escaped, and bounded to `WINDOW`
589/// characters with the cut said, so a pasted clause cannot make the refusal
590/// bigger than the request it answers.
591fn quoted_anchor(anchor: &str) -> String {
592    let count = anchor.chars().count();
593    if count <= WINDOW {
594        return shown(anchor);
595    }
596    let head: String = anchor.chars().take(WINDOW).collect();
597    format!(
598        "{}\u{2026} (+{} more characters)",
599        shown(&head),
600        count - WINDOW
601    )
602}
603
604/// Bounded context around `[start, end)`: up to `WINDOW` characters on
605/// either side of the matched span, and up to `WINDOW` characters of the
606/// span itself (the caller's own anchor, echoed back bounded).
607fn around(working: &str, start: usize, end: usize) -> Context {
608    let matched = &working[start..end];
609    let matched_cut = matched.chars().count() > WINDOW;
610    let matched: String = matched.chars().take(WINDOW).collect();
611    let before: String = working[..start].chars().rev().take(WINDOW).collect();
612    let before: String = before.chars().rev().collect();
613    let after: String = working[end..].chars().take(WINDOW).collect();
614    Context::new(before, matched, after).with_truncated(
615        matched_cut
616            || working[..start].chars().count() > WINDOW
617            || working[end..].chars().count() > WINDOW,
618    )
619}
620
621/// `{n} {word}` or `{n} {word}s`.
622fn plural(n: usize, word: &str) -> String {
623    format!("{n} {word}{}", if n == 1 { "" } else { "s" })
624}
625
626/// `jubarte read …` argv: the program, the task, the source path when known,
627/// and `options`. A path that starts with `-` would parse as an option, so it
628/// goes last, after `--`, and the argv stays executable as given. Without a
629/// path the continuation says what is missing.
630fn read_action(refusal: &AnchorRefusal<'_>, options: [String; 2]) -> NextAction {
631    let mut argv = vec!["jubarte".to_string(), "read".to_string()];
632    match refusal.path {
633        Some(path) if path.starts_with('-') => {
634            argv.extend(options);
635            argv.extend(["--".to_string(), path.to_string()]);
636            NextAction::new(argv)
637        }
638        Some(path) => {
639            argv.push(path.to_string());
640            argv.extend(options);
641            NextAction::new(argv)
642        }
643        None => {
644            argv.extend(options);
645            NextAction::new(argv).with_prerequisites(vec![
646                "the source file path (the refusal binds its digest)".to_string(),
647            ])
648        }
649    }
650}
651
652/// The read continuation for the requested target.
653fn read_target(refusal: &AnchorRefusal<'_>) -> NextAction {
654    read_action(refusal, ["-p".to_string(), refusal.target.to_string()])
655        .with_purpose(format!("read the actual text of {}", refusal.target))
656}
657
658/// The bounded read continuation for a target that does not exist.
659fn read_head(refusal: &AnchorRefusal<'_>) -> NextAction {
660    read_action(
661        refusal,
662        ["--head".to_string(), READ_SUGGESTION_HEAD.to_string()],
663    )
664    .with_purpose("list the paragraphs that exist, bounded".to_string())
665}
666
667/// The read continuation that offers a candidate elsewhere — a suggestion,
668/// never a retarget.
669fn suggest_read(refusal: &AnchorRefusal<'_>, id: &str, hits: usize) -> NextAction {
670    let mut action = read_action(refusal, ["-p".to_string(), id.to_string()]);
671    let mut prerequisites = action.prerequisites.take().unwrap_or_default();
672    prerequisites.push("re-targeting is the caller's decision".to_string());
673    action
674        .with_purpose(format!(
675            "suggestion only: the anchor occurs {hits} times in {id}; a supplied target is never retargeted"
676        ))
677        .with_prerequisites(prerequisites)
678}
679
680#[cfg(test)]
681#[cfg_attr(all(coverage_nightly, test), coverage(off))]
682mod tests {
683    use super::*;
684
685    #[test]
686    fn a_miss_shows_the_bounded_start_of_the_target() {
687        assert_eq!(bounded_start("0123456789"), "0123456789");
688        let long = "x".repeat(WINDOW + 5);
689        assert_eq!(bounded_start(&long).chars().count(), WINDOW);
690    }
691
692    #[test]
693    fn a_match_context_is_banded_on_both_sides() {
694        let text = format!("{}y{}z", "a".repeat(WINDOW + 3), "b".repeat(WINDOW + 7));
695        let start = WINDOW + 3;
696        let end = start + 1;
697        let context = around(&text, start, end);
698        assert_eq!(context.matched, "y");
699        assert_eq!(context.before.chars().count(), WINDOW);
700        assert_eq!(context.after.chars().count(), WINDOW);
701        assert!(context.truncated);
702        let context = around("abcYdef", 3, 4);
703        assert_eq!(
704            (
705                context.before.as_str(),
706                context.matched.as_str(),
707                context.after.as_str()
708            ),
709            ("abc", "Y", "def")
710        );
711        assert!(!context.truncated);
712    }
713
714    #[test]
715    fn a_pasted_clause_anchor_is_quoted_bounded() {
716        let short = "needle";
717        assert_eq!(quoted_anchor(short), shown(short));
718        let clause = "c".repeat(3 * WINDOW);
719        let quoted = quoted_anchor(&clause);
720        assert!(!quoted.contains(&clause), "{quoted}");
721        assert_eq!(
722            quoted,
723            format!(
724                "{}\u{2026} (+{} more characters)",
725                shown(&"c".repeat(WINDOW)),
726                2 * WINDOW
727            )
728        );
729        // The matched span of a long anchor is bounded too, and says so.
730        let text = clause.clone();
731        let context = around(&text, 0, text.len());
732        assert_eq!(context.matched, "c".repeat(WINDOW));
733        assert!(context.truncated);
734    }
735
736    #[test]
737    fn counts_are_pluralized() {
738        assert_eq!(plural(1, "paragraph"), "1 paragraph");
739        assert_eq!(plural(2, "revision"), "2 revisions");
740    }
741}