strop-engine 0.25.0

strop editor engine: documents, grammar dispatch, services, sessions — no terminal
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
//! Editable code collections (0044): picker results as one real buffer of
//! source excerpts. Edits to an excerpt write back to its source document
//! through the change-plan gateway at action boundaries; generated headers
//! are protected, and a source that moved on refuses by name.

#[cfg(test)]
mod tests;

use std::collections::HashMap;
use std::path::PathBuf;

use strop_core::id::{Arena, BufferRevision, DocumentId, DocumentKind};
use strop_core::{Buffer, Range};
use strop_workspace::ResourceLocation;

use super::changes::{ChangePlan, ChangeProducer, PlannedDocument};
use super::document::Document;
use super::Editor;

/// One excerpt: a whole-line span of a source document, remapped through
/// the source's change journal like any other saved anchor.
#[derive(Debug, Clone)]
pub(crate) struct Excerpt {
    pub source: DocumentId,
    /// Source byte span (whole lines), remapped on every source mutation.
    pub start: usize,
    pub end: usize,
    /// FNV-1a of the span's bytes at build/regeneration — the write-back
    /// staleness check.
    pub fingerprint: u64,
    /// Header line index in the shadow text (the title is line 0).
    pub view_line: usize,
    /// Source line count as rendered into the shadow.
    pub view_lines: usize,
    /// Body byte span in the view/shadow text (0049 §5 invalidation:
    /// source changes splice this span directly).
    pub view_start: usize,
    pub view_end: usize,
}

#[derive(Debug, Clone)]
pub(crate) struct Collection {
    pub title: String,
    pub excerpts: Vec<Excerpt>,
    /// Source saves in flight from a collection `:w`/`:wq`; the view
    /// closes only when every one confirms (0049 §5).
    pub pending_saves: usize,
    pub close_when_saved: bool,
    /// The canonical rendering as of the last sync. The sync diff is
    /// shadow vs current — no hidden state.
    pub shadow: String,
    /// The buffer revision at last sync — the cheap no-change check that
    /// keeps motions from materializing rope text on the input path.
    pub revision: BufferRevision,
}

/// An in-flight collection build: hits plus the count of background
/// source loads still outstanding (0044 v2 async source loading).
#[derive(Debug)]
pub(crate) struct CollectionBuild {
    pub title: String,
    pub hits: Vec<(std::path::PathBuf, usize)>,
    /// Remote hits resolve against open remote documents at build.
    pub remote_hits: Vec<(strop_workspace::RemoteEndpoint, std::path::PathBuf, usize)>,
    pub waiting: usize,
}

fn fingerprint(text: &str) -> u64 {
    let mut hash: u64 = 0xcbf29ce484222325;
    for byte in text.as_bytes() {
        hash = (hash ^ u64::from(*byte)).wrapping_mul(0x100000001b3);
    }
    hash
}

/// The canonical rendering: title, then per excerpt a header line and its
/// source text. Re-anchors each excerpt's view span as it is emitted. An
/// associated function over disjoint fields, so the map entry can be
/// re-anchored while the editor borrows `docs` and `cwd`.
fn render(
    docs: &Arena<DocumentKind, Document>,
    cwd: &std::path::Path,
    collection: &mut Collection,
) -> String {
    let mut text = format!(
        "collection: {}{} excerpt(s) (edits write back at action boundaries; g<Space> opens source)\n",
        collection.title,
        collection.excerpts.len()
    );
    let mut line = 1;
    for excerpt in &mut collection.excerpts {
        let source = &docs.get(excerpt.source).unwrap().buf;
        let path = source
            .path
            .as_ref()
            .map(|path| path.strip_prefix(cwd).unwrap_or(path).display().to_string())
            .unwrap_or_else(|| "[scratch]".into());
        let first = source.line_of(excerpt.start) + 1;
        text.push_str(&format!("── {path}:{first} ──\n"));
        let body = source
            .text()
            .byte_slice(excerpt.start..excerpt.end)
            .to_string();
        #[cfg(test)]
        eprintln!(
            "render excerpt src={:?} span={}..{} body={body:?}",
            excerpt.source, excerpt.start, excerpt.end
        );
        excerpt.view_line = line;
        excerpt.view_start = text.len();
        excerpt.view_lines = body.lines().count().max(1);
        excerpt.fingerprint = fingerprint(&body);
        text.push_str(&body);
        if !body.ends_with('\n') {
            text.push('\n');
        }
        excerpt.view_end = text.len();
        line += 1 + excerpt.view_lines;
    }
    text
}

impl Editor {
    /// `ctrl-o` in a result picker: open the listed hits as an editable
    /// collection. Hits whose files are not open local documents are
    /// counted and skipped with a message; remote hits carry no local
    /// payload, so they are skipped the same way.
    pub(crate) fn open_collection_from_picker(&mut self) {
        let Some(glue) = &self.picker else {
            return;
        };
        let kind = glue.picker.kind;
        if !matches!(
            kind,
            strop_picker::Kind::Locations
                | strop_picker::Kind::Diagnostics
                | strop_picker::Kind::Grep
        ) {
            self.message = "collections come from a results list".into();
            return;
        }
        // Local hits and remote hits alike; remote ones resolve against
        // open remote documents (0040 permits gate their write-back).
        let mut hits: Vec<(std::path::PathBuf, usize)> = Vec::new();
        let mut remote_hits: Vec<(strop_workspace::RemoteEndpoint, std::path::PathBuf, usize)> =
            Vec::new();
        for item in glue.picker.items.iter() {
            match &item.payload {
                strop_picker::Payload::Grep { path, line, .. } => {
                    hits.push((path.clone(), line.saturating_sub(1)));
                }
                strop_picker::Payload::Remote {
                    endpoint,
                    path,
                    line,
                    ..
                } => remote_hits.push((endpoint.clone(), path.clone(), line.saturating_sub(1))),
                _ => {}
            }
        }
        let title = kind.title().trim().to_string();
        self.close_picker();
        // Unopened sources load in the background (never switching focus);
        // the build assembles when the last one lands.
        let mut to_load: Vec<std::path::PathBuf> = Vec::new();
        for (path, _) in &hits {
            let absolute = if path.is_absolute() {
                path.clone()
            } else {
                self.cwd.join(path)
            };
            let open = self.docs.iter().any(|(_, doc)| {
                doc.matches_target(&crate::files::FileTarget::Local(absolute.clone()))
            });
            if !open && !to_load.contains(&absolute) {
                to_load.push(absolute);
            }
        }
        let waiting = to_load.len();
        let build = CollectionBuild {
            title,
            hits,
            remote_hits,
            waiting,
        };
        if to_load.is_empty() {
            self.build_collection(build);
            return;
        }
        self.collection_build = Some(build);
        self.message = format!("collection: loading {waiting} source(s)…");
        for path in to_load {
            self.request_open(path, crate::editor::io::OpenIntent::Background);
        }
    }

    /// A background source load landed (or failed): the pending build
    /// counts down and assembles when its sources are all in.
    pub(crate) fn collection_source_ready(&mut self, _document: DocumentId) {
        let Some(build) = &mut self.collection_build else {
            strop_trace::record_with(
                strop_trace::EventKind::JobFinished,
                || serde_json::json!({"service":"collection","result":"ready-without-build"}),
            );
            return;
        };
        build.waiting = build.waiting.saturating_sub(1);
        strop_trace::record_with(
            strop_trace::EventKind::JobFinished,
            || serde_json::json!({"service":"collection","result":"source-ready","waiting":build.waiting}),
        );
        if build.waiting == 0 {
            let build = self.collection_build.take().unwrap();
            self.build_collection(build);
        }
    }

    fn build_collection(&mut self, build: CollectionBuild) {
        let CollectionBuild {
            title,
            hits,
            remote_hits,
            ..
        } = build;
        let mut by_doc: HashMap<DocumentId, Vec<usize>> = HashMap::new();
        let mut skipped = 0;
        for (path, line) in hits {
            let absolute = if path.is_absolute() {
                path
            } else {
                self.cwd.join(path)
            };
            let Some(document) = self.docs.iter().find_map(|(id, doc)| {
                doc.matches_target(&crate::files::FileTarget::Local(absolute.clone()))
                    .then_some(id)
            }) else {
                skipped += 1;
                continue;
            };
            by_doc.entry(document).or_default().push(line);
        }
        for (endpoint, path, line) in remote_hits {
            let document = self.docs.iter().find_map(|(id, doc)| {
                doc.remote_metadata().and_then(|source| {
                    (source.file.endpoint() == &endpoint && source.file.path() == path.as_path())
                        .then_some(id)
                })
            });
            match document {
                Some(id) => by_doc.entry(id).or_default().push(line),
                None => skipped += 1,
            }
        }
        if by_doc.is_empty() {
            self.message = "no open buffers among the results — open them first".into();
            return;
        }
        let mut excerpts = Vec::new();
        for (source, mut lines) in by_doc {
            lines.sort_unstable();
            lines.dedup();
            let buf = &self.docs.get(source).unwrap().buf;
            // Merge adjacent lines into one excerpt so an edit never
            // applies twice to overlapping spans.
            let mut spans: Vec<(usize, usize)> = Vec::new();
            for line in lines {
                if line >= buf.len_lines() {
                    continue;
                }
                match spans.last_mut() {
                    Some((_, end)) if line <= *end => *end = line + 1,
                    _ => spans.push((line, line + 1)),
                }
            }
            for (start_line, end_line) in spans {
                let start = buf.line_start(start_line);
                let end = if end_line >= buf.len_lines() {
                    buf.len_bytes()
                } else {
                    buf.line_start(end_line)
                };
                let text = buf.text().byte_slice(start..end).to_string();
                excerpts.push(Excerpt {
                    source,
                    start,
                    end,
                    fingerprint: fingerprint(&text),
                    view_line: 0,
                    view_lines: 0,
                    view_start: 0,
                    view_end: 0,
                });
            }
        }
        excerpts.sort_by_key(|excerpt| (excerpt.source, excerpt.start));
        let excerpt_count = excerpts.len();
        let title_for_trace = title.clone();
        let id = self.docs.insert(Document::output(Buffer::from_text("")));
        // The modeline names the collection, never [scratch] (0049 §6).
        self.docs.get_mut(id).unwrap().buf.name = Some(format!("collection: {title}"));
        let mut collection = Collection {
            title,
            excerpts,
            pending_saves: 0,
            close_when_saved: false,
            shadow: String::new(),
            revision: BufferRevision::new(0),
        };
        let text = render(&self.docs, &self.cwd, &mut collection);
        collection.shadow = text.clone();
        self.collections.insert(id, collection);
        let _ = self.doc_mut(id).buf.system_edit().replace_all(&text);
        self.docs.get_mut(id).unwrap().buf.readonly = false;
        let revision = self.docs.get(id).unwrap().buf.revision();
        self.collections.get_mut(&id).unwrap().revision = revision;
        strop_trace::record_with(strop_trace::EventKind::JobFinished, || {
            serde_json::json!({
                "service":"collection","result":"built","excerpts":excerpt_count,
                "skipped":skipped,"title":title_for_trace,
            })
        });
        self.drop_stale_scratch(id);
        self.switch_to(id);
        self.set_head(0);
        self.message = match skipped {
            0 => format!("collection: {excerpt_count} excerpt(s)"),
            _ => format!("collection built; {skipped} hit(s) skipped (not open local buffers)"),
        };
    }

    /// Every normal-mode action boundary in a collection buffer is a
    /// write-back attempt — gated on the buffer revision so motions and
    /// in-progress insert typing never materialize rope text.
    pub(crate) fn maybe_sync_collection(&mut self) {
        if self.docs.is_empty() {
            return;
        }
        let id = self.current();
        let revision = self.buf().revision();
        let Some(stored) = self.collections.get(&id).map(|c| c.revision) else {
            return;
        };
        if revision == stored {
            return;
        }
        let current = self.buf().text().to_string();
        if current == self.collections[&id].shadow {
            self.collections.get_mut(&id).unwrap().revision = revision;
            return;
        }
        // Write-back against a working copy; the entry stays in the map
        // so the change-journal remap still tracks its anchors mid-apply.
        let working = self.collections[&id].clone();
        if let Err(reason) = self.collection_write_back(&working, &current) {
            self.message = reason;
        }
        let open = working
            .excerpts
            .iter()
            .all(|excerpt| self.docs.get(excerpt.source).is_some());
        if !open {
            self.message = "collection: a source buffer was closed — view dropped".into();
            self.collections.remove(&id);
            return;
        }
        // The source is authoritative: regenerate the view and reset the
        // shadow whether or not the write-back landed.
        self.collection_render_view(id);
    }

    /// Re-render the collection view from its sources and reset shadow +
    /// revision together (0049 §5: no stale text may be presented).
    pub(crate) fn collection_render_view(&mut self, id: DocumentId) {
        // Preserve the logical caret across the regeneration (0049 §5):
        // same row/column clamped into the new text.
        let caret = if self.current() == id {
            Some((
                self.buf().line_of(self.head()),
                self.buf().col_of(self.head()),
            ))
        } else {
            None
        };
        let text = {
            let entry = self.collections.get_mut(&id).unwrap();
            render(&self.docs, &self.cwd, entry)
        };
        {
            let entry = self.collections.get_mut(&id).unwrap();
            entry.shadow = text.clone();
        }
        let _ = self.doc_mut(id).buf.system_edit().replace_all(&text);
        if let Some((line, col)) = caret {
            let line = line.min(self.docs.get(id).unwrap().buf.len_lines().saturating_sub(1));
            let head = self.docs.get(id).unwrap().buf.clamp_boundary(
                self.docs
                    .get(id)
                    .unwrap()
                    .buf
                    .line_start(line)
                    .saturating_add(col),
            );
            if self.current() == id {
                self.set_head(head);
                self.clamp_cursor();
            }
        }
        let revision = self.docs.get(id).unwrap().buf.revision();
        self.collections.get_mut(&id).unwrap().revision = revision;
        // The view is a presentation: its dirty bit is never the story
        // (0049 §5 — the sources own unsaved state).
        self.docs.get_mut(id).unwrap().buf.dirty = false;
    }

    /// A source change strictly inside one excerpt (0049 §5): splice the
    /// excerpt's view span with the new source body instead of
    /// re-rendering the whole view. The caller gates on a clean view
    /// (no unsynced user edit) — the spans assume shadow == view.
    pub(crate) fn collection_splice_excerpt(&mut self, id: DocumentId, index: usize) {
        let (source, view_start, view_end, view_lines) = {
            let entry = &self.collections[&id];
            let excerpt = &entry.excerpts[index];
            (
                excerpt.source,
                excerpt.view_start,
                excerpt.view_end,
                excerpt.view_lines,
            )
        };
        let Some(source_doc) = self.docs.get(source) else {
            return;
        };
        let excerpt_span = {
            let entry = &self.collections[&id];
            let excerpt = &entry.excerpts[index];
            (excerpt.start, excerpt.end)
        };
        let mut body = source_doc
            .buf
            .text()
            .byte_slice(excerpt_span.0..excerpt_span.1)
            .to_string();
        #[cfg(test)]
        eprintln!("splice coll={id:?} ex={index} span={excerpt_span:?} view={view_start}..{view_end} body={body:?}");
        if !body.ends_with('\n') {
            body.push('\n');
        }
        let new_lines = body.lines().count().max(1);
        // Splice the collection buffer at the excerpt's view span; the
        // view is clean, so the spans index it directly.
        {
            let doc = self.docs.get_mut(id).unwrap();
            let _ = doc
                .buf
                .system_edit()
                .replace(Range::charwise(view_start, view_end), &body);
        }
        // The splice's own journal entry feeds the view analysis and is
        // then consumed: the write-back diff must never see it.
        {
            let doc = self.docs.get_mut(id).unwrap();
            let changes: Vec<_> = doc.buf.changes().to_vec();
            self.analysis.edits(id, &changes);
            doc.buf.clear_changes();
        }
        let byte_delta = body.len() as isize - (view_end - view_start) as isize;
        let line_delta = new_lines as isize - view_lines as isize;
        let entry = self.collections.get_mut(&id).unwrap();
        // Shadow moves with the view, byte-identical region.
        entry.shadow.replace_range(view_start..view_end, &body);
        let mut seen = false;
        for excerpt in &mut entry.excerpts {
            if seen {
                excerpt.view_start = (excerpt.view_start as isize + byte_delta) as usize;
                excerpt.view_end = (excerpt.view_end as isize + byte_delta) as usize;
                excerpt.view_line = (excerpt.view_line as isize + line_delta) as usize;
            } else if excerpt.view_start == view_start {
                seen = true;
                excerpt.view_lines = new_lines;
                excerpt.view_end = view_start + body.len();
                excerpt.fingerprint = fingerprint(&body);
            }
        }
        let revision = self.docs.get(id).unwrap().buf.revision();
        self.collections.get_mut(&id).unwrap().revision = revision;
    }
    /// Line-level diff: common prefix/suffix lines trim first (0049 §5 —
    /// the 2,000-excerpt audit stall was the full-view O(n²) LCS on a
    /// one-line edit); the dynamic table only ever sees the changed
    /// middle. Disjoint edit regions in one batch fall back to the LCS
    /// over that middle only.
    fn diff_lines(
        shadow: &[&str],
        current: &[&str],
    ) -> Vec<(std::ops::Range<usize>, std::ops::Range<usize>)> {
        let prefix = shadow
            .iter()
            .zip(current.iter())
            .take_while(|(a, b)| a == b)
            .count();
        let suffix = shadow[prefix..]
            .iter()
            .rev()
            .zip(current[prefix.min(current.len())..].iter().rev())
            .take_while(|(a, b)| a == b)
            .count();
        let smid = &shadow[prefix..shadow.len() - suffix.min(shadow.len() - prefix)];
        let cmid = &current[prefix..current.len() - suffix.min(current.len() - prefix)];
        if smid.is_empty() && cmid.is_empty() {
            return Vec::new();
        }
        Self::diff_lines_middle(
            &shadow[prefix..prefix + smid.len()],
            &current[prefix..prefix + cmid.len()],
        )
        .into_iter()
        .map(|(old, new)| {
            (
                old.start + prefix..old.end + prefix,
                new.start + prefix..new.end + prefix,
            )
        })
        .collect()
    }

    /// The LCS table over the changed middle only.
    fn diff_lines_middle(
        shadow: &[&str],
        current: &[&str],
    ) -> Vec<(std::ops::Range<usize>, std::ops::Range<usize>)> {
        let (n, m) = (shadow.len(), current.len());
        // lcs[i][j] = LCS length of shadow[i..] vs current[j..]
        let mut lcs = vec![vec![0usize; m + 1]; n + 1];
        for i in (0..n).rev() {
            for j in (0..m).rev() {
                lcs[i][j] = if shadow[i] == current[j] {
                    lcs[i + 1][j + 1] + 1
                } else {
                    lcs[i + 1][j].max(lcs[i][j + 1])
                };
            }
        }
        let mut hunks = Vec::new();
        let (mut i, mut j) = (0, 0);
        while i < n || j < m {
            if i < n && j < m && shadow[i] == current[j] {
                i += 1;
                j += 1;
                continue;
            }
            let (si, sj) = (i, j);
            while i < n || j < m {
                if i < n && j < m && shadow[i] == current[j] {
                    break;
                }
                if i < n && (j == m || lcs[i + 1][j] >= lcs[i][j + 1]) {
                    i += 1;
                } else {
                    j += 1;
                }
            }
            hunks.push((si..i, sj..j));
        }
        hunks
    }

    /// A shadow line's position in the current text, given the hunks.
    /// An insertion exactly AT the line attaches forward: span starts map
    /// without it (the inserted text joins the span), span ends with it.
    fn map_line(
        hunks: &[(std::ops::Range<usize>, std::ops::Range<usize>)],
        line: usize,
        count_at_boundary: bool,
    ) -> usize {
        let mut current = line;
        for (old, new) in hunks {
            let counts =
                old.end < line || (old.end == line && (!old.is_empty() || count_at_boundary));
            if counts {
                current += new.len() - old.len();
            } else {
                break;
            }
        }
        current
    }

    /// Diff shadow vs current and write back every touched excerpt as one
    /// change plan (0044 v2: multiple regions across excerpts, one batch
    /// per source document). Structure lines (title, headers) are never
    /// editable; a hunk touching one refuses the whole sync.
    fn collection_write_back(
        &mut self,
        collection: &Collection,
        current: &str,
    ) -> Result<(), String> {
        let shadow_lines: Vec<&str> = collection.shadow.split_inclusive('\n').collect();
        let current_lines: Vec<&str> = current.split_inclusive('\n').collect();
        let hunks = Self::diff_lines(&shadow_lines, &current_lines);
        if hunks.is_empty() {
            return Ok(());
        }
        // Every hunk must sit fully inside one excerpt's body span.
        let mut touched: Vec<usize> = Vec::new();
        for (old, _) in &hunks {
            let mut owner = None;
            for (index, excerpt) in collection.excerpts.iter().enumerate() {
                let lo = excerpt.view_line + 1;
                let hi = excerpt.view_line + excerpt.view_lines + 1;
                let inside = if old.is_empty() {
                    // an insertion belongs to a body only inside it
                    old.start >= lo && old.start < hi
                } else {
                    old.start >= lo && old.end <= hi
                };
                if inside {
                    owner = Some(index);
                    break;
                }
                // Overlap without containment crosses a boundary.
                if !old.is_empty() && old.start < hi && old.end > lo {
                    return Err(
                        "edit touches a header or spans excerpts — refused; view refreshed".into(),
                    );
                }
            }
            let Some(index) = owner else {
                return Err(
                    "edit touches the title, a header, or the collection's structure — refused; view refreshed"
                        .into(),
                );
            };
            if !touched.contains(&index) {
                touched.push(index);
            }
        }
        // One replacement per touched excerpt: its whole body span as it
        // currently reads — partial hunks carry their unchanged context.
        let mut by_source: Vec<(DocumentId, Vec<strop_core::Replacement>, ResourceLocation)> =
            Vec::new();
        for index in touched {
            let excerpt = &collection.excerpts[index];
            let source = self
                .docs
                .get(excerpt.source)
                .ok_or_else(|| "collection: a source buffer was closed".to_string())?;
            let present = source
                .buf
                .text()
                .byte_slice(excerpt.start..excerpt.end)
                .to_string();
            if fingerprint(&present) != excerpt.fingerprint {
                return Err(
                    "collection: a source changed elsewhere — refused; view refreshed".into(),
                );
            }
            if source.buf.readonly {
                return Err(
                    "collection: a source is read-only (remote sources need :remote edit first) — refused; view refreshed"
                        .into(),
                );
            }
            let lo = excerpt.view_line + 1;
            let hi = excerpt.view_line + excerpt.view_lines + 1;
            let cur_lo = Self::map_line(&hunks, lo, false);
            let cur_hi = Self::map_line(&hunks, hi, true);
            let mut replacement: String = current_lines[cur_lo..cur_hi].concat();
            if !replacement.is_empty() && !replacement.ends_with('\n') {
                replacement.push('\n');
            }
            let edit = strop_core::Replacement::new(
                Range::charwise(excerpt.start, excerpt.end),
                replacement,
            );
            let location = match &source.source {
                super::document::DocumentSource::Remote(remote) => ResourceLocation::remote(
                    remote.file.endpoint().clone(),
                    remote.file.path().to_path_buf(),
                ),
                _ => ResourceLocation::local(source.buf.path.clone().unwrap_or_default()),
            };
            match by_source
                .iter_mut()
                .find(|(id, _, _)| *id == excerpt.source)
            {
                Some((_, edits, _)) => edits.push(edit),
                None => by_source.push((excerpt.source, vec![edit], location)),
            }
        }
        let documents = by_source
            .into_iter()
            .map(|(document, edits, location)| PlannedDocument {
                location,
                document,
                base: self.docs.get(document).unwrap().buf.revision(),
                edits,
            })
            .collect();
        let plan = ChangePlan {
            producer: ChangeProducer::CollectionEdit,
            documents,
            refused: Vec::new(),
        };
        self.apply_change_plan(plan);
        Ok(())
    }
}

impl Editor {
    /// `u` in a collection (0049 §5): undo the newest edit group that
    /// came FROM this collection, across its actual sources. Preflight
    /// every member — a source edited since refuses the whole group by
    /// name, and the receipt is never consumed on refusal.
    pub(crate) fn collection_undo(&mut self) {
        let id = self.current();
        let Some(sources) = self
            .collections
            .get(&id)
            .map(|c| c.excerpts.iter().map(|e| e.source).collect::<Vec<_>>())
        else {
            return;
        };
        let Some((index, mut receipt)) = self.changes.take_newest_matching(|receipt| {
            receipt.producer == "collection edit"
                && receipt
                    .applied
                    .iter()
                    .any(|(document, ..)| sources.contains(document))
        }) else {
            self.message = "already at oldest change".into();
            return;
        };
        let mut moved = 0;
        for (document, _before, after) in &receipt.applied {
            match self.docs.get(*document) {
                Some(doc) if doc.buf.revision() == *after => {}
                Some(_) => {
                    let name = self
                        .docs
                        .get(*document)
                        .and_then(|d| d.buf.path.clone())
                        .map(|p| p.display().to_string())
                        .unwrap_or_else(|| "a source".into());
                    self.changes.restore(index, receipt);
                    self.message =
                        format!("collection undo refused: {name} changed since — resolve it first");
                    return;
                }
                None => {
                    self.changes.restore(index, receipt);
                    self.message = "collection undo refused: a source buffer was closed".into();
                    return;
                }
            }
        }
        let mut depths = Vec::with_capacity(receipt.applied.len());
        for (document, ..) in &receipt.applied {
            let undone_ok = matches!(self.doc_mut(*document).buf.undo(), Ok(Some(_)));
            if undone_ok {
                moved += 1;
            }
            depths.push(
                self.docs
                    .get(*document)
                    .map(|doc| doc.buf.history().depth())
                    .unwrap_or(0),
            );
        }
        receipt.redo_depths = Some(depths);
        // The undo's own journal refreshes the dependent views (0049 §5
        // invalidation) — no explicit render here.
        self.changes.push_undone(receipt);
        self.message = format!("undid collection edit across {moved} buffer(s)");
    }

    /// `ctrl-r` in a collection: redo the newest undone group of this
    /// collection, same preflight rules as undo.
    pub(crate) fn collection_redo(&mut self) {
        let id = self.current();
        let Some(sources) = self
            .collections
            .get(&id)
            .map(|c| c.excerpts.iter().map(|e| e.source).collect::<Vec<_>>())
        else {
            return;
        };
        let Some(receipt) = self.changes.take_undone_matching(|receipt| {
            receipt
                .applied
                .iter()
                .any(|(document, ..)| sources.contains(document))
        }) else {
            self.message = "nothing to redo".into();
            return;
        };
        // Revisions are monotonic — an undo never returns to one — so
        // preflight the undone position by history depth (0049 §5).
        let depths = receipt.redo_depths.clone();
        for (member, (document, ..)) in receipt.applied.iter().enumerate() {
            let at = self
                .docs
                .get(*document)
                .map(|doc| doc.buf.history().depth());
            if at != depths.as_ref().map(|d| d[member]) {
                self.changes.push_undone(receipt);
                self.message = "collection redo refused: a source changed since the undo".into();
                return;
            }
        }
        let mut moved = 0;
        for (document, ..) in &receipt.applied {
            if matches!(self.doc_mut(*document).buf.redo(), Ok(Some(_))) {
                moved += 1;
            }
        }
        self.changes.push_receipt_back(receipt);
        self.message = format!("redid collection edit across {moved} buffer(s)");
    }
}

impl Editor {
    /// `:w` in a collection (0049 §5): save the dirty SOURCES through
    /// their own save paths — never the presentation. `:w PATH` refuses:
    /// the view is not a file and exporting it is not this operation.
    pub(crate) fn collection_save(&mut self, target: Option<PathBuf>, force: bool, close: bool) {
        let id = self.current();
        if target.is_some() {
            self.message = "a collection has no file of its own — :w saves its sources;                             exporting the view is unsupported"
                .into();
            return;
        }
        let Some(sources) = self.collections.get(&id).map(|c| {
            let mut seen: Vec<DocumentId> = c.excerpts.iter().map(|e| e.source).collect();
            seen.dedup();
            seen
        }) else {
            return;
        };
        let mut queued = 0;
        let mut refused: Vec<String> = Vec::new();
        for source in sources {
            let Some(doc) = self.docs.get(source) else {
                continue;
            };
            if !doc.buf.dirty {
                continue;
            }
            let name = doc
                .buf
                .path
                .as_ref()
                .map(|p| p.display().to_string())
                .unwrap_or_else(|| "[scratch]".into());
            if doc.buf.readonly {
                refused.push(name);
                continue;
            }
            // Readonly/remote-permit refusals stay authoritative inside
            // the save path itself (0040); :w! grants no new capability.
            self.request_save_document(source, None, force, false);
            queued += 1;
        }
        if let Some(collection) = self.collections.get_mut(&id) {
            collection.pending_saves = queued;
            collection.close_when_saved = close && refused.is_empty() && queued > 0;
        }
        if queued == 0 && refused.is_empty() {
            if close {
                self.close_pane_or_buffer(false);
            } else {
                self.message = "collection: all sources are saved".into();
            }
            return;
        }
        if !refused.is_empty() {
            self.message = format!(
                "collection: saving {queued} source(s); read-only skipped: {}",
                refused.join(", ")
            );
        } else {
            self.message = format!("collection: saving {queued} source(s)");
        }
    }

    /// A source save completed (0049 §5): count down; the `:wq` view
    /// closes only when every save confirmed. A failure cancels the
    /// close and stays visible.
    pub(crate) fn collection_save_progress(&mut self, document: DocumentId, saved: bool) {
        let mut close: Option<DocumentId> = None;
        for (id, collection) in self.collections.iter_mut() {
            if collection.pending_saves == 0
                || !collection.excerpts.iter().any(|e| e.source == document)
            {
                continue;
            }
            if !saved {
                collection.pending_saves = 0;
                collection.close_when_saved = false;
                continue;
            }
            collection.pending_saves = collection.pending_saves.saturating_sub(1);
            if collection.pending_saves == 0 && collection.close_when_saved {
                close = Some(*id);
            }
        }
        if let Some(id) = close {
            if self.current() == id {
                self.close_pane_or_buffer(false);
            } else if let Some(collection) = self.collections.get_mut(&id) {
                collection.close_when_saved = false;
                self.message = "collection: sources saved".into();
            }
        }
    }
}

impl Editor {
    /// `g<Space>` in a collection, Enter on a header row, and
    /// `:collection source` (0049 §5): open the full source under the
    /// caret — the live document with its unsaved edits, never a disk
    /// reload. A body row maps to the exact source position; a header
    /// row opens the file at that excerpt's first line. The jump is
    /// recorded so Ctrl-O returns to the collection working context.
    pub fn collection_open_source_pub(&mut self) {
        self.collection_open_source();
    }

    pub(crate) fn collection_open_source(&mut self) {
        let id = self.current();
        let cursor_line = self.buf().line_of(self.head());
        let cursor_col = self.buf().col_of(self.head());
        let Some(collection) = self.collections.get(&id) else {
            return;
        };
        let mut target: Option<(DocumentId, usize)> = None;
        for excerpt in &collection.excerpts {
            if cursor_line == excerpt.view_line {
                // header row: the file, at this excerpt's first line
                target = Some((excerpt.source, excerpt.start));
                break;
            }
            if cursor_line > excerpt.view_line
                && cursor_line <= excerpt.view_line + excerpt.view_lines
            {
                // body row: same line-in-excerpt, same column
                let Some(source) = self.docs.get(excerpt.source) else {
                    break;
                };
                let source_line =
                    source.buf.line_of(excerpt.start) + (cursor_line - excerpt.view_line - 1);
                let line = source_line.min(source.buf.len_lines().saturating_sub(1));
                target = Some((
                    excerpt.source,
                    source
                        .buf
                        .clamp_boundary(source.buf.line_start(line).saturating_add(cursor_col)),
                ));
                break;
            }
        }
        let Some((document, head)) = target else {
            self.message = "not on an excerpt".into();
            return;
        };
        if self.docs.get(document).is_none() {
            self.message = "collection: that source was closed".into();
            return;
        }
        self.push_jump();
        self.switch_to(document);
        self.set_head(head);
        self.clamp_cursor();
        self.scroll_to_cursor(self.view_rows());
    }
}

impl Editor {
    /// The SOURCE line number for a collection view row (0049 §6):
    /// Some(Some(n)) for body rows, Some(None) for chrome (title,
    /// headers — the gutter stays blank there), None for ordinary
    /// buffers.
    pub fn collection_source_lineno(
        &self,
        doc: strop_core::id::DocumentId,
        line: usize,
    ) -> Option<Option<usize>> {
        let collection = self.collections.get(&doc)?;
        for excerpt in &collection.excerpts {
            if line == excerpt.view_line {
                return Some(None); // header row
            }
            if line > excerpt.view_line && line <= excerpt.view_line + excerpt.view_lines {
                let source = self.docs.get(excerpt.source)?;
                let first = source.buf.line_of(excerpt.start);
                return Some(Some(first + (line - excerpt.view_line - 1) + 1));
            }
        }
        Some(None) // title row
    }
}