strop-editor 0.6.0

strop — a modal text editor in Rust: see the cut before you make it
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
//! Git working surface (M2, hunk preview reworked 0010): hunks between
//! HEAD and the live buffer, refreshed on edit epochs; hunk nav and the
//! hunk verbs.

use strop_git::{Hunk, HunkKind, Repo, Sign};

use super::git_memory::HunkOrigin;
use super::Editor;

/// What a hunk verb (`Space g u`/`g s`) targets from the current view.
enum HunkTarget {
    /// Not on a hunk surface: act on the cursor's own buffer.
    NotASurface,
    /// A hunk preview whose origin buffer still matches the epoch it
    /// was captured at.
    Fresh {
        buffer: strop_core::id::DocumentId,
        hunk: Hunk,
    },
    /// The origin buffer changed since the preview opened — applying
    /// the stored region would cut the wrong lines.
    Stale,
}

impl Editor {
    /// Discover the repo for the current buffer (once per buffer switch).
    pub(crate) fn discover_git(&mut self) {
        let from = self
            .buf()
            .path
            .as_deref()
            .map(std::path::PathBuf::from)
            .unwrap_or_else(|| self.cwd.clone());
        self.git = Repo::discover(&from);
        self.hunks.clear();
        self.hunks_epoch = u64::MAX;
    }

    /// Recompute hunks when the buffer changed since the last diff.
    /// libgit2 in-memory diff — no process spawn per keystroke (0001 §3).
    pub fn refresh_hunks(&mut self) {
        let Some(repo) = &self.git else {
            return;
        };
        let epoch = self.buf().epoch;
        if epoch == self.hunks_epoch {
            return;
        }
        let path = self.buf().path.clone();
        // the four states (0014 wave 4): unstaged = index↔live, staged
        // = HEAD↔index — two edges, two sign sets
        self.hunks = match &path {
            Some(p) => repo.unstaged_hunks(std::path::Path::new(p), &self.buf().rope.to_string()),
            None => vec![],
        };
        self.staged_hunks = match &path {
            Some(p) => repo.staged_hunks(std::path::Path::new(p)),
            None => vec![],
        };
        self.hunks_epoch = epoch;
    }

    /// Gutter sign for a 1-based buffer line: `+` add, `~` change,
    /// `-` deletion below (0001 pillar 3.1).
    pub fn sign_at(&self, line_1based: usize) -> Option<char> {
        let total = self.buf().len_lines();
        for h in &self.hunks {
            for (l, kind) in h.signs() {
                let matched = match kind {
                    Sign::AddOrChange => l == line_1based,
                    Sign::DeleteAfter => l.min(total) == line_1based,
                };
                if matched {
                    return Some(match kind {
                        Sign::DeleteAfter => '-',
                        Sign::AddOrChange => {
                            if h.kind == HunkKind::Add {
                                '+'
                            } else {
                                '~'
                            }
                        }
                    });
                }
            }
        }
        None
    }

    /// Staged sign (HEAD↔index edge, 0014 wave 4): the line sits inside
    /// a staged hunk's new side. Line alignment between index and live
    /// text is approximate when both sets exist — the gutter's rule:
    /// unstaged wins, staged marks what's already in the index.
    pub fn sign_at_staged(&self, line_1based: usize) -> bool {
        self.staged_hunks.iter().any(|h| {
            h.lines.iter().any(|l| {
                l.origin == strop_git::LineOrigin::Addition && l.new_lineno == Some(line_1based)
            })
        })
    }

    /// `]c` / `[c`: jump to the next/previous changed line.
    pub(crate) fn jump_hunk(&mut self, forward: bool) {
        self.refresh_hunks();
        let cur = self.buf().line_of(self.head()) + 1;
        let total = self.buf().len_lines();
        let mut lines: Vec<usize> = self
            .hunks
            .iter()
            .flat_map(|h| h.signs().iter().map(|&(l, _)| l).collect::<Vec<_>>())
            .map(|l| l.min(total))
            .collect();
        lines.sort_unstable();
        lines.dedup();
        let target = if forward {
            lines.iter().copied().find(|&l| l > cur)
        } else {
            lines.iter().copied().rev().find(|&l| l < cur)
        };
        match target {
            Some(l) => {
                self.set_head(self.buf().line_start(l - 1));
                self.clamp_cursor();
            }
            None => self.message = "no more hunks".into(),
        }
    }

    /// The hunk under the cursor, if any.
    fn hunk_under_cursor(&mut self) -> Option<Hunk> {
        self.refresh_hunks();
        let line = self.buf().line_of(self.head()) + 1;
        let total = self.buf().len_lines();
        self.hunks.iter().find(|h| h.covers(line, total)).cloned()
    }

    /// Apply `hunk`'s reverse to buffer `idx`: pure deletions reinsert,
    /// pure additions drop, changes swap old content back. Returns
    /// false when the buffer has no HEAD content to restore from.
    fn restore_hunk_in(&mut self, idx: strop_core::id::DocumentId, hunk: &Hunk) -> bool {
        let Some(path) = self.doc(idx).buf.path.clone() else {
            return false;
        };
        let Some(repo) = &self.git else { return false };
        // undo's edge is live/worktree ← index (discard UNSTAGED); with
        // nothing staged the index IS HEAD (0014 wave 4)
        let Some(head) = repo
            .index_content(std::path::Path::new(&path))
            .or_else(|| repo.head_content(std::path::Path::new(&path)))
        else {
            return false;
        };
        let head_lines: Vec<&str> = head.lines().collect();
        let (new_first, new_count, old_first, old_count) = hunk.changed_region();
        // only computed when restoring (change/delete); pure adds need
        // none — and a top-of-file add has old_first == 0, so the `- 1`
        // math must stay saturating
        let old: String = if old_count == 0 {
            String::new()
        } else {
            let lo = old_first.saturating_sub(1).min(head_lines.len());
            let hi = (lo + old_count).min(head_lines.len());
            head_lines[lo..hi.max(lo)].join("\n")
        };

        let saved_current = self.current();
        self.view_mut().doc = idx;
        if new_count == 0 {
            // pure deletion: reinsert the old lines at the gap
            let total = self.buf().len_lines();
            if new_first > total {
                let end = self.buf().len_bytes();
                self.buf_mut().insert(end, &format!("\n{old}"));
            } else {
                let at = self.buf().line_start(new_first.saturating_sub(1));
                self.buf_mut().insert(at, &format!("{old}\n"));
            }
            self.set_head(self.buf().line_start(new_first.saturating_sub(1)));
        } else if old_count == 0 {
            // pure addition: drop the added lines
            let start = self.buf().line_start(new_first - 1);
            let last = (new_first - 1 + new_count).min(self.buf().len_lines());
            let end = if last >= self.buf().len_lines() {
                self.buf().len_bytes()
            } else {
                self.buf().line_start(last)
            };
            self.buf_mut()
                .delete(strop_core::Range::charwise(start, end));
            self.set_head(
                self.buf()
                    .line_start((new_first - 1).min(self.buf().len_lines() - 1)),
            );
        } else {
            let start = self.buf().line_start(new_first - 1);
            let end = self
                .buf()
                .line_end((new_first - 1 + new_count - 1).min(self.buf().len_lines() - 1));
            self.buf_mut()
                .delete(strop_core::Range::charwise(start, end));
            self.buf_mut().insert(start, &old);
            self.set_head(start);
        }
        self.view_mut().doc = saved_current;
        // the cursor field belongs to the driven pane; only the origin
        // buffer's own view moves when it is current
        if self.current() == idx {
            self.clamp_cursor();
            self.flash(strop_core::Range::charwise(self.head(), self.head()));
        } else {
            let at = {
                let buf = &self.doc(idx).buf;
                buf.line_start(buf.len_lines().saturating_sub(1))
            };
            if let Some(pane) = self.panes.iter_mut().find(|p| p.doc == idx) {
                pane.sels.collapse_primary(at);
            }
        }
        true
    }

    /// `Space g u`: reset a hunk to HEAD's content. From the hunk
    /// surface it restores the origin buffer's hunk (0010 §2).
    pub(crate) fn undo_hunk(&mut self) {
        match self.hunk_surface_target() {
            HunkTarget::Fresh { buffer, hunk } => {
                if self.restore_hunk_in(buffer, &hunk) {
                    self.message = "hunk reset".into();
                }
            }
            HunkTarget::Stale => self.message = "buffer changed — reopen the hunk preview".into(),
            HunkTarget::NotASurface => {
                let Some(hunk) = self.hunk_under_cursor() else {
                    self.message = "no hunk here".into();
                    return;
                };
                if self.restore_hunk_in(self.current(), &hunk) {
                    self.message = "hunk reset".into();
                }
            }
        }
    }

    /// `Space g s`: stage a hunk (git apply --cached). From the hunk
    /// surface it stages the origin buffer's hunk.
    pub(crate) fn stage_hunk(&mut self) {
        match self.hunk_surface_target() {
            HunkTarget::Fresh { buffer, hunk } => self.stage_hunk_in(buffer, &hunk),
            HunkTarget::Stale => self.message = "buffer changed — reopen the hunk preview".into(),
            HunkTarget::NotASurface => {
                let Some(hunk) = self.hunk_under_cursor() else {
                    self.message = "no hunk here".into();
                    return;
                };
                self.stage_hunk_in(self.current(), &hunk);
            }
        }
    }

    fn stage_hunk_in(&mut self, idx: strop_core::id::DocumentId, hunk: &Hunk) {
        let Some(path) = self.doc(idx).buf.path.clone() else {
            return;
        };
        // staging reads the *disk* file's hunk: a dirty buffer means the
        // two disagree, and auto-saving would silently write every
        // unrelated unsaved edit to the worktree (0014). Refuse loudly.
        if self.doc(idx).buf.dirty {
            self.message = "unsaved changes — :w first, then stage".into();
            return;
        }
        let Some(repo) = &self.git else { return };
        let Ok(rel) = std::path::Path::new(&path)
            .strip_prefix(repo.workdir())
            .map(|p| p.to_path_buf())
        else {
            self.message = "buffer not under workdir".into();
            return;
        };
        match repo.stage_hunk(&rel, hunk) {
            Ok(()) => {
                self.hunks_epoch = u64::MAX;
                self.message = "hunk staged".into();
            }
            Err(e) => self.message = format!("stage failed: {e}"),
        }
    }

    /// `Space g S`: unstage the hunk under the cursor — the
    /// index→HEAD edge. Needs a staged hunk under the cursor (the
    /// staged set's lines are index-numbered; find its hunk by line).
    pub(crate) fn unstage_hunk(&mut self) {
        if self.buf().dirty {
            self.message = "unsaved changes — :w first".into();
            return;
        }
        let line = self.buf().line_of(self.head()) + 1;
        let Some(hunk) = self
            .staged_hunks
            .iter()
            .find(|h| h.covers(line, self.buf().len_lines()))
            .cloned()
        else {
            self.message = "no staged hunk here".into();
            return;
        };
        let Some(path) = self.buf().path.clone() else {
            return;
        };
        let Some(repo) = &self.git else { return };
        let Ok(rel) = std::path::Path::new(&path)
            .strip_prefix(repo.workdir())
            .map(|p| p.to_path_buf())
        else {
            self.message = "buffer not under workdir".into();
            return;
        };
        match repo.unstage_hunk(&rel, &hunk) {
            Ok(()) => {
                self.hunks_epoch = u64::MAX;
                self.message = "hunk unstaged".into();
            }
            Err(e) => self.message = format!("unstage failed: {e}"),
        }
    }

    /// `Space g p`: preview the hunk under the cursor as a diff surface
    /// (0010 §2) — a readonly buffer you can move in; `q` closes,
    /// `Space g u`/`g s` still act on the file.
    pub(crate) fn preview_hunk(&mut self) {
        let Some(hunk) = self.hunk_under_cursor() else {
            self.message = "no hunk here".into();
            return;
        };
        let origin = HunkOrigin {
            buffer: self.current(),
            epoch: self.cur().buf.epoch,
        };
        self.open_diff_surface("hunk", "hunk", vec![hunk], Some(origin));
    }

    /// What a `Space g u`/`g s` from the current buffer should act on:
    /// the hunk surface's origin when fresh, a refusal when the origin
    /// buffer has moved on, and the cursor's own hunk otherwise.
    fn hunk_surface_target(&self) -> HunkTarget {
        let Some(super::Surface::Diff { hunks, origin, .. }) = self.surface() else {
            return HunkTarget::NotASurface;
        };
        let Some(origin) = origin else {
            return HunkTarget::NotASurface; // commit delta: nothing to undo
        };
        let Some(hunk) = hunks.first() else {
            return HunkTarget::NotASurface;
        };
        match self.docs.get(origin.buffer) {
            Some(d) if d.buf.epoch == origin.epoch => HunkTarget::Fresh {
                buffer: origin.buffer,
                hunk: hunk.clone(),
            },
            _ => HunkTarget::Stale,
        }
    }

    pub(crate) fn feed_git_pending(&mut self, c: char) {
        self.pending.clear();
        match c {
            'u' => self.undo_hunk(),
            's' => self.stage_hunk(),
            // unstage: the index→HEAD edge (0014 wave 4 names edges)
            'S' => self.unstage_hunk(),
            'p' => self.preview_hunk(),
            'l' => self.open_log(false),
            'h' => self.open_log(true),
            'b' => self.toggle_blame_gutter(),
            'y' => self.yank_permalink(),
            'o' => self.open_permalink(),
            _ => {
                self.message =
                    "Space g: l log · h file history · b blame · y/o permalink · u/s/p hunk".into()
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use std::process::Command;

    use super::*;
    use crate::editor::Key;
    use crate::editor::Surface;
    use strop_core::Buffer;

    /// A git repo with one committed file, edited in-memory.
    fn fixture() -> (tempfile::TempDir, Editor) {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        for args in [
            vec!["init", "-q"],
            vec!["config", "user.email", "t@t.t"],
            vec!["config", "user.name", "t"],
        ] {
            Command::new("git")
                .args(&args)
                .current_dir(root)
                .output()
                .unwrap();
        }
        std::fs::write(root.join("f.rs"), "fn a() {}\nfn b() {}\n").unwrap();
        Command::new("git")
            .args(["add", "."])
            .current_dir(root)
            .output()
            .unwrap();
        Command::new("git")
            .args(["commit", "-qm", "init"])
            .current_dir(root)
            .output()
            .unwrap();
        let mut e = Editor::new(Buffer::open(root.join("f.rs").to_str().unwrap()).unwrap());
        e.discover_git();
        (dir, e)
    }

    #[test]
    fn gutter_tracks_live_edits() {
        let (_d, mut e) = fixture();
        e.refresh_hunks();
        assert_eq!(e.sign_at(1), None, "clean buffer has no signs");
        e.feed_text("G");
        e.feed_text("ofn c() {}");
        e.feed_text("<esc>");
        e.refresh_hunks();
        assert_eq!(e.sign_at(3), Some('+'), "added line signs +");
        assert_eq!(e.sign_at(1), None);
    }

    #[test]
    fn hunk_nav_and_undo() {
        let (_d, mut e) = fixture();
        e.feed_text("Go");
        e.feed_text("fn c() {}");
        e.feed_text("<esc>");
        e.feed_text("gg");
        e.jump_hunk(true);
        assert_eq!(e.buf().line_of(e.head()) + 1, 3, "]c lands on the hunk");
        e.undo_hunk();
        assert_eq!(e.buf().rope.to_string(), "fn a() {}\nfn b() {}\n");
    }

    #[test]
    fn space_g_namespace_dispatches() {
        let (_d, mut e) = fixture();
        e.feed_text("G");
        e.feed_text("o");
        for c in "fn new() {}".chars() {
            e.feed(Key::Char(c));
        }
        e.feed(Key::Esc);
        e.feed_text(" gp"); // Space, g, p
        assert!(
            matches!(e.surface(), Some(Surface::Diff { .. })),
            "Space g p opens the hunk surface (buffer: {})",
            e.buf().rope
        );
    }

    /// The hunk surface is a real readonly buffer you can move in, and
    /// ` g u` from it restores the origin buffer (0010 §2).
    #[test]
    fn hunk_surface_moves_and_undoes() {
        let (_d, mut e) = fixture();
        e.feed_text("Go");
        e.feed_text("fn c() {}");
        e.feed_text("<esc>");
        e.feed_text("]c"); // like the tape: jump onto the hunk first
        e.feed_text(" gp");
        assert!(e.buf().readonly);
        assert!(e.buf().rope.to_string().contains("fn c() {}"));
        // motions work on the hunk surface
        e.feed_text("j");
        e.feed_text("j");
        assert_eq!(e.buf().line_of(e.head()), 2);
        // undo acts on the origin file buffer, not the surface
        e.feed_text(" gu");
        let text = e.doc(e.first_doc()).buf.rope.to_string();
        assert_eq!(text, "fn a() {}\nfn b() {}\n", "hunk restored: {text}");
        e.feed_text("q");
        assert_eq!(e.current(), e.first_doc());
    }

    /// 0014 P0: staging must never silently write unrelated unsaved
    /// edits — a dirty buffer refuses with a pointer to :w.
    #[test]
    fn stage_refuses_a_dirty_buffer() {
        let (d, mut e) = fixture();
        e.feed_text("Go");
        e.feed_text("fn c() {}");
        e.feed_text("<esc>gg]c");
        e.feed_text(" gs");
        assert!(
            e.message.contains(":w first"),
            "dirty stage refuses: {}",
            e.message
        );
        let staged = Command::new("git")
            .args(["diff", "--cached", "--stat"])
            .current_dir(d.path())
            .output()
            .unwrap();
        assert!(
            staged.stdout.is_empty(),
            "nothing reached the index: {}",
            String::from_utf8_lossy(&staged.stdout)
        );
        // after an explicit save, staging works
        e.feed_text(":w\r");
        e.feed_text(" gs");
        assert!(e.message.contains("staged"), "{}", e.message);
    }

    /// A stale preview refuses honestly: edits after opening it change
    /// the epoch, and applying the stored region would cut wrong.
    #[test]
    fn stale_hunk_surface_refuses() {
        let (_d, mut e) = fixture();
        e.feed_text("Go");
        e.feed_text("fn c() {}");
        e.feed_text("<esc>gg]c gp");
        // edit the origin document: the epoch moves, the preview goes stale
        // (the active pane's document IS the current one — the surface —
        // so point a second pane at the file for the cursor-keep branch)
        e.panes.push(crate::editor::Pane {
            doc: e.first_doc(),
            sels: strop_core::selection::SelectionSet::default(),
            view_top: 0,
        });
        e.doc_mut(e.first_doc()).buf.insert(0, "// touched\n");
        e.feed_text(" gu");
        assert!(
            e.message.contains("buffer changed"),
            "stale preview must refuse: {}",
            e.message
        );
    }

    /// 0014 wave 4: the full edge dance by keys — edit, save, stage,
    /// unstage; the index is the witness.
    #[test]
    fn stage_and_unstage_name_their_edges() {
        let (d, mut e) = fixture();
        e.feed_text("Gofn c() {}");
        e.feed_text("<esc>");
        e.feed_text(":w\r");
        e.feed_text("]c gs");
        assert!(e.message.contains("staged"), "{}", e.message);
        let staged = Command::new("git")
            .args(["diff", "--cached", "--stat"])
            .current_dir(d.path())
            .output()
            .unwrap();
        assert!(!staged.stdout.is_empty(), "hunk in the index");
        // staged set drives the gutter's committed-adjacent tint
        e.refresh_hunks();
        assert!(e.sign_at_staged(3), "staged line marked");
        assert!(e.sign_at(3).is_none(), "not also unstaged");
        e.feed_text(" gS");
        assert!(e.message.contains("unstaged"), "{}", e.message);
        let staged = Command::new("git")
            .args(["diff", "--cached", "--stat"])
            .current_dir(d.path())
            .output()
            .unwrap();
        assert!(staged.stdout.is_empty(), "index back to HEAD");
        // and now the same line reads as unstaged again
        e.refresh_hunks();
        assert_eq!(e.sign_at(3), Some('+'));
    }
}