From 57dfac80eb60099444174a014f2a5eb959382318 Mon Sep 17 00:00:00 2001 From: Pablo Speciale Date: Sat, 14 Nov 2026 16:46:56 +0100 Subject: [PATCH 01/32] feat: parse delta's OSC 1717 line metadata Set OSC1717=V1 for delta and, when its output starts with the handshake, attach each row's line records to the diff line and strip them from the text. Older delta ignores the variable and renders as before. --- pkg/ui/panes/diffviewer/delta_args_test.go | 8 +- pkg/ui/panes/diffviewer/diffviewer.go | 18 +++-- pkg/ui/panes/diffviewer/osc1717.go | 77 ++++++++++++++++++ pkg/ui/panes/diffviewer/osc1717_test.go | 91 ++++++++++++++++++++++ 4 files changed, 184 insertions(+), 10 deletions(-) create mode 100644 pkg/ui/panes/diffviewer/osc1717.go create mode 100644 pkg/ui/panes/diffviewer/osc1717_test.go diff --git a/pkg/ui/panes/diffviewer/delta_args_test.go b/pkg/ui/panes/diffviewer/delta_args_test.go index dfe3c84..a72da48 100644 --- a/pkg/ui/panes/diffviewer/delta_args_test.go +++ b/pkg/ui/panes/diffviewer/delta_args_test.go @@ -35,11 +35,15 @@ func TestMakeDeltaArgs(t *testing.T) { func TestMakeDeltaEnv(t *testing.T) { t.Setenv("GIT_CONFIG_PARAMETERS", "'delta.navigate'='true'") - if got := makeDeltaEnv(deltaOpts{SideBySide: true}); !slices.Equal(got, os.Environ()) { - t.Fatalf("themed: expected the plain environment, got %q", got) + wantEnv := append(os.Environ(), "OSC1717=V1") + if got := makeDeltaEnv(deltaOpts{SideBySide: true}); !slices.Equal(got, wantEnv) { + t.Fatalf("themed: expected %q, got %q", wantEnv, got) } env := makeDeltaEnv(deltaOpts{UseUserDeltaTheme: true}) + if !slices.Contains(env, "OSC1717=V1") { + t.Errorf("user delta theme: expected OSC1717=V1 in %q", env) + } got := env[len(env)-1] want := "GIT_CONFIG_PARAMETERS='delta.navigate'='true' 'delta.side-by-side'='false'" if got != want { diff --git a/pkg/ui/panes/diffviewer/diffviewer.go b/pkg/ui/panes/diffviewer/diffviewer.go index 9eaf45b..3908f2a 100644 --- a/pkg/ui/panes/diffviewer/diffviewer.go +++ b/pkg/ui/panes/diffviewer/diffviewer.go @@ -42,7 +42,8 @@ func cacheKey(path string, sideBySide bool) string { } type diffLine struct { - item item.Item + item item.Item + records []record } func (o diffLine) GetItem() item.Item { @@ -488,7 +489,7 @@ func (m *Model) diffFile(node *cachedNode, width int) tea.Cmd { return common.ErrMsg{Err: err} } - return diffContentMsg{cacheKey: key, node: node, lines: stringToDiffLines(string(out))} + return diffContentMsg{cacheKey: key, node: node, lines: parseDeltaOutput(string(out))} } } @@ -522,11 +523,11 @@ func (m *Model) diffDir(dir *cachedNode, width int, sideBySide bool, preamble st return common.ErrMsg{Err: err} } - text := string(out) + lines := parseDeltaOutput(string(out)) if preamble != "" { - text = m.renderPreamble(preamble) + "\n" + text + lines = append(stringToDiffLines(m.renderPreamble(preamble)), lines...) } - return diffContentMsg{cacheKey: key, node: dir, lines: stringToDiffLines(text)} + return diffContentMsg{cacheKey: key, node: dir, lines: lines} } } @@ -623,10 +624,11 @@ type deltaOpts struct { UseUserDeltaTheme bool } -// makeDeltaEnv sets side-by-side like `git -c delta.side-by-side=...` would. -// The --side-by-side flag would override the user's line-number format and can't turn it off. +// makeDeltaEnv asks for OSC 1717 line metadata and, with the user's theme, sets side-by-side +// like `git -c delta.side-by-side=...` would. The --side-by-side flag would override the +// user's line-number format and can't turn it off. func makeDeltaEnv(opts deltaOpts) []string { - env := os.Environ() + env := append(os.Environ(), "OSC1717=V1") if !opts.UseUserDeltaTheme { return env } diff --git a/pkg/ui/panes/diffviewer/osc1717.go b/pkg/ui/panes/diffviewer/osc1717.go new file mode 100644 index 0000000..e73d373 --- /dev/null +++ b/pkg/ui/panes/diffviewer/osc1717.go @@ -0,0 +1,77 @@ +package diffviewer + +import ( + "strconv" + "strings" + + "github.com/robinovitch61/viewport/viewport/item" +) + +// OSC 1717 diff line metadata (https://github.com/stefanhaller/diff-line-metadata-spec). +// Delta >= 0.20 emits it when OSC1717=V1 is set; older versions ignore the variable. +const ( + osc1717Prefix = "\x1b]1717;" + osc1717Term = "\x1b\\" + osc1717Handshake = osc1717Prefix + "1" + osc1717Term +) + +// record says which diff line a row shows. +// Kind is c (context), a (added), d (deleted), f (file header) or h (hunk header). +type record struct { + Kind byte + NewLine int + OldLine int + File string +} + +// parseDeltaOutput splits delta's output into rows. When it starts with the +// OSC 1717 handshake, each row's records are parsed and stripped from its text. +func parseDeltaOutput(out string) []diffLine { + rest, ok := strings.CutPrefix(out, osc1717Handshake) + if !ok { + return stringToDiffLines(out) + } + rest = strings.TrimPrefix(rest, "\n") + rows := strings.Split(rest, "\n") + lines := make([]diffLine, len(rows)) + for i, row := range rows { + text, records := parseRecords(row) + lines[i] = diffLine{item: item.NewItem(text), records: records} + } + return lines +} + +// parseRecords removes the OSC 1717 sequences from a row and returns them. +func parseRecords(row string) (string, []record) { + var records []record + var b strings.Builder + for { + start := strings.Index(row, osc1717Prefix) + if start < 0 { + break + } + end := strings.Index(row[start:], osc1717Term) + if end < 0 { + break + } + b.WriteString(row[:start]) + if r, ok := parseRecord(row[start+len(osc1717Prefix) : start+end]); ok { + records = append(records, r) + } + row = row[start+end+len(osc1717Term):] + } + b.WriteString(row) + return b.String(), records +} + +// parseRecord parses ";;;;". +func parseRecord(body string) (record, bool) { + fields := strings.SplitN(body, ";", 5) + if len(fields) != 5 || fields[0] != "1" || len(fields[1]) != 1 || + !strings.Contains("cadfh", fields[1]) { + return record{}, false + } + newLine, _ := strconv.Atoi(fields[2]) + oldLine, _ := strconv.Atoi(fields[3]) + return record{Kind: fields[1][0], NewLine: newLine, OldLine: oldLine, File: fields[4]}, true +} diff --git a/pkg/ui/panes/diffviewer/osc1717_test.go b/pkg/ui/panes/diffviewer/osc1717_test.go new file mode 100644 index 0000000..ac3aa41 --- /dev/null +++ b/pkg/ui/panes/diffviewer/osc1717_test.go @@ -0,0 +1,91 @@ +package diffviewer + +import ( + "os/exec" + "reflect" + "strings" + "testing" +) + +func osc(body string) string { return osc1717Prefix + body + osc1717Term } + +func TestParseDeltaOutput(t *testing.T) { + out := osc1717Handshake + "\n" + + osc("1;f;;;a.go") + "a.go\n" + + osc("1;h;10;;a.go") + "@@\n" + + "\x1b[0m────\n" + + osc("1;d;10;9;a.go") + "\x1b[31m-x" + osc("1;a;10;;a.go") + "+y\n" + + osc("1;c;11;;dir;b.go") + " z\n" + + osc("1;C;;;abc123") + osc("2;c;1;;a.go") + "commit" + + lines := parseDeltaOutput(out) + if len(lines) != 6 { + t.Fatalf("expected 6 rows, got %d", len(lines)) + } + want := [][]record{ + {{Kind: 'f', File: "a.go"}}, + {{Kind: 'h', NewLine: 10, File: "a.go"}}, + nil, + {{Kind: 'd', NewLine: 10, OldLine: 9, File: "a.go"}, {Kind: 'a', NewLine: 10, File: "a.go"}}, + {{Kind: 'c', NewLine: 11, File: "dir;b.go"}}, + nil, // unknown type and version + } + for i, l := range lines { + if !reflect.DeepEqual(l.records, want[i]) { + t.Errorf("row %d: expected %+v, got %+v", i, want[i], l.records) + } + } +} + +func TestParseRecords_StripsText(t *testing.T) { + text, _ := parseRecords(osc("1;d;10;9;a.go") + "\x1b[31m-x" + osc("1;a;10;;a.go") + "+y") + if text != "\x1b[31m-x+y" { + t.Fatalf("expected records stripped, got %q", text) + } +} + +func TestParseDeltaOutput_NoHandshake(t *testing.T) { + lines := parseDeltaOutput("plain\n" + osc("1;c;1;;a.go") + " x") + if len(lines) != 2 || lines[1].records != nil { + t.Fatalf("expected no records without the handshake, got %+v", lines) + } +} + +func TestParseDeltaOutput_RealDelta(t *testing.T) { + if _, err := exec.LookPath("delta"); err != nil { + t.Skip("delta not installed") + } + t.Setenv("GIT_CONFIG_PARAMETERS", "") + t.Setenv("GIT_CONFIG_GLOBAL", "/dev/null") + t.Setenv("GIT_CONFIG_NOSYSTEM", "1") + patch := "diff --git a/a;b.go b/a;b.go\n--- a/a;b.go\n+++ b/a;b.go\n" + + "@@ -1,2 +1,2 @@\n ctx\n-old\n+new\n" + cmd := exec.Command("delta", "--paging=never", "--side-by-side", "-w=80") + cmd.Env = makeDeltaEnv(deltaOpts{}) + cmd.Stdin = strings.NewReader(patch) + out, err := cmd.Output() + if err != nil { + t.Fatalf("delta: %v", err) + } + if !strings.HasPrefix(string(out), osc1717Handshake) { + t.Skip("delta has no OSC 1717 support") + } + + var got []record + for _, l := range parseDeltaOutput(string(out)) { + for _, r := range l.records { + if r.Kind == 'c' || r.Kind == 'a' || r.Kind == 'd' { + got = append(got, r) + } + } + } + want := []record{ + {Kind: 'c', NewLine: 1, File: "a;b.go"}, + {Kind: 'c', NewLine: 1, File: "a;b.go"}, + {Kind: 'd', NewLine: 2, OldLine: 2, File: "a;b.go"}, + {Kind: 'a', NewLine: 2, File: "a;b.go"}, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("expected %+v, got %+v", want, got) + } +} From b6f55b372c448a0899c2538c407f51d0d22cb5c3 Mon Sep 17 00:00:00 2001 From: Pablo Speciale Date: Sat, 14 Nov 2026 16:50:16 +0100 Subject: [PATCH 02/32] fix: keep the first row that carries the OSC 1717 handshake Delta writes the handshake in front of its first row, not on a row of its own. --- pkg/ui/panes/diffviewer/osc1717.go | 4 ++-- pkg/ui/panes/diffviewer/osc1717_test.go | 3 +-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/pkg/ui/panes/diffviewer/osc1717.go b/pkg/ui/panes/diffviewer/osc1717.go index e73d373..7956a9c 100644 --- a/pkg/ui/panes/diffviewer/osc1717.go +++ b/pkg/ui/panes/diffviewer/osc1717.go @@ -25,13 +25,13 @@ type record struct { } // parseDeltaOutput splits delta's output into rows. When it starts with the -// OSC 1717 handshake, each row's records are parsed and stripped from its text. +// OSC 1717 handshake (a prefix of the first row, not a row of its own), each +// row's records are parsed and stripped from its text. func parseDeltaOutput(out string) []diffLine { rest, ok := strings.CutPrefix(out, osc1717Handshake) if !ok { return stringToDiffLines(out) } - rest = strings.TrimPrefix(rest, "\n") rows := strings.Split(rest, "\n") lines := make([]diffLine, len(rows)) for i, row := range rows { diff --git a/pkg/ui/panes/diffviewer/osc1717_test.go b/pkg/ui/panes/diffviewer/osc1717_test.go index ac3aa41..a3b4925 100644 --- a/pkg/ui/panes/diffviewer/osc1717_test.go +++ b/pkg/ui/panes/diffviewer/osc1717_test.go @@ -10,8 +10,7 @@ import ( func osc(body string) string { return osc1717Prefix + body + osc1717Term } func TestParseDeltaOutput(t *testing.T) { - out := osc1717Handshake + "\n" + - osc("1;f;;;a.go") + "a.go\n" + + out := osc1717Handshake + osc("1;f;;;a.go") + "a.go\n" + osc("1;h;10;;a.go") + "@@\n" + "\x1b[0m────\n" + osc("1;d;10;9;a.go") + "\x1b[31m-x" + osc("1;a;10;;a.go") + "+y\n" + From 45d9dacf1d05941ee450b11fb8655d96025b5b15 Mon Sep 17 00:00:00 2001 From: Pablo Speciale Date: Sat, 14 Nov 2026 16:52:55 +0100 Subject: [PATCH 03/32] feat: keep the scroll position when toggling side-by-side or resizing Remember the diff line at the top of the view (or the selected one) and, once the re-rendered diff is shown, scroll back to the row with the same OSC 1717 record. Keeping the row index drifted, since unified and side-by-side lay out a different number of rows. Without records the index is kept as before. --- pkg/ui/panes/diffviewer/diffviewer.go | 52 ++++++++++++++++++-- pkg/ui/panes/diffviewer/osc1717.go | 42 +++++++++++++++++ pkg/ui/panes/diffviewer/osc1717_test.go | 63 +++++++++++++++++++++++++ 3 files changed, 154 insertions(+), 3 deletions(-) diff --git a/pkg/ui/panes/diffviewer/diffviewer.go b/pkg/ui/panes/diffviewer/diffviewer.go index 3908f2a..1a0ace7 100644 --- a/pkg/ui/panes/diffviewer/diffviewer.go +++ b/pkg/ui/panes/diffviewer/diffviewer.go @@ -96,6 +96,8 @@ type Model struct { useUserDeltaTheme bool preamble string sb common.Scrollbar + // anchor is the diff line to scroll back to once the re-rendered diff is shown. + anchor *record } // SetPreamble stores the preamble text (e.g. commit metadata from git show). @@ -229,7 +231,7 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { } node.diff = msg.lines if node == m.file || node == m.dir { - m.fvp.SetObjects(msg.lines) + m.setLines(msg.lines) } } @@ -262,15 +264,56 @@ func (m *Model) SetSize(width, height int) tea.Cmd { m.Height = height m.fvp.SetWidth(m.contentWidth()) m.fvp.SetHeight(m.Height) + m.keepPosition() m.ClearCache() return m.diff() } func (m *Model) UpdateTheme() tea.Cmd { + m.keepPosition() m.ClearCache() return m.diff() } +// keepPosition remembers the diff line at the top of the view (or the selected one), +// so the next render of this node scrolls back to it. +func (m *Model) keepPosition() { + node := m.file + if node == nil { + node = m.dir + } + if node == nil || m.fvp.GetMatchingItemsOnly() { + return + } + row := m.fvp.GetItemMetrics().FirstVisibleItemIdx + if m.SelectionEnabled() { + row = m.fvp.GetSelectedItemIdx() + } + // Keep a pending anchor if the current render hasn't arrived yet. + if rec, ok := firstRecord(node.diff, row); ok { + m.anchor = &rec + } +} + +// setLines shows lines and scrolls to the anchor, if any. +func (m *Model) setLines(lines []diffLine) { + m.fvp.SetObjects(lines) + if m.anchor == nil { + return + } + row := findRecord(lines, *m.anchor) + m.anchor = nil + if row < 0 || m.fvp.GetMatchingItemsOnly() { + return + } + if m.SelectionEnabled() { + m.fvp.SetSelectedItemIdx(row) + return + } + m.fvp.GoToTop() + m.fvp.ScrollDown(row) +} + func (m Model) contentWidth() int { return m.Width - scrollbarWidth } @@ -282,7 +325,7 @@ func (m *Model) diff() tea.Cmd { key := cacheKey(m.file.path, sideBySide) if cached, ok := m.cache[key]; ok && len(cached.diff) != 0 { m.file = cached - m.fvp.SetObjects(cached.diff) + m.setLines(cached.diff) return nil } node := &cachedNode{ @@ -298,7 +341,7 @@ func (m *Model) diff() tea.Cmd { key := cacheKey(m.dir.path, m.sideBySide) if cached, ok := m.cache[key]; ok && len(cached.diff) != 0 { m.dir = cached - m.fvp.SetObjects(cached.diff) + m.setLines(cached.diff) return nil } node := &cachedNode{ @@ -364,6 +407,7 @@ func (m Model) dirHeaderView() string { func (m Model) SetFilePatch(file *gitdiff.File) (Model, tea.Cmd) { m.dir = nil + m.anchor = nil fname := filenode.GetFileName(file) sideBySide := m.sideBySide && !file.IsNew && !file.IsDelete @@ -392,6 +436,7 @@ func (m Model) SetFilePatch(file *gitdiff.File) (Model, tea.Cmd) { func (m Model) SetDirPatch(dirPath string, files []*gitdiff.File) (Model, tea.Cmd) { m.file = nil + m.anchor = nil key := cacheKey(dirPath, m.sideBySide) if cached, ok := m.cache[key]; ok { @@ -429,6 +474,7 @@ func (m *Model) updateHeader() { // SetSideBySide updates the diff view mode and re-renders. func (m *Model) SetSideBySide(sideBySide bool) tea.Cmd { m.sideBySide = sideBySide + m.keepPosition() return m.diff() } diff --git a/pkg/ui/panes/diffviewer/osc1717.go b/pkg/ui/panes/diffviewer/osc1717.go index 7956a9c..0ef39da 100644 --- a/pkg/ui/panes/diffviewer/osc1717.go +++ b/pkg/ui/panes/diffviewer/osc1717.go @@ -75,3 +75,45 @@ func parseRecord(body string) (record, bool) { oldLine, _ := strconv.Atoi(fields[3]) return record{Kind: fields[1][0], NewLine: newLine, OldLine: oldLine, File: fields[4]}, true } + +// firstRecord returns the first record at or below row. +func firstRecord(lines []diffLine, row int) (record, bool) { + for i := max(row, 0); i < len(lines); i++ { + if len(lines[i].records) > 0 { + return lines[i].records[0], true + } + } + return record{}, false +} + +// findRecord returns the first row showing the same diff line as want, else the +// first row at or after its line in the same file, else -1. +func findRecord(lines []diffLine, want record) int { + nearest := -1 + for i, l := range lines { + for _, r := range l.records { + if r.File != want.File { + continue + } + if sameLine(r, want) { + return i + } + if nearest < 0 && want.Kind != 'f' && r.Kind != 'f' && r.NewLine >= want.NewLine { + nearest = i + } + } + } + return nearest +} + +// sameLine compares records of the same file: d by old line, c/a and h by new line. +func sameLine(r, want record) bool { + switch want.Kind { + case 'd': + return r.Kind == 'd' && r.OldLine == want.OldLine + case 'c', 'a': + return (r.Kind == 'c' || r.Kind == 'a') && r.NewLine == want.NewLine + default: + return r.Kind == want.Kind && r.NewLine == want.NewLine + } +} diff --git a/pkg/ui/panes/diffviewer/osc1717_test.go b/pkg/ui/panes/diffviewer/osc1717_test.go index a3b4925..6f051f4 100644 --- a/pkg/ui/panes/diffviewer/osc1717_test.go +++ b/pkg/ui/panes/diffviewer/osc1717_test.go @@ -5,6 +5,9 @@ import ( "reflect" "strings" "testing" + + "github.com/bluekeyes/go-gitdiff/gitdiff" + "github.com/robinovitch61/viewport/viewport/item" ) func osc(body string) string { return osc1717Prefix + body + osc1717Term } @@ -88,3 +91,63 @@ func TestParseDeltaOutput_RealDelta(t *testing.T) { t.Fatalf("expected %+v, got %+v", want, got) } } + +func row(records ...record) diffLine { + return diffLine{item: item.NewItem("x"), records: records} +} + +func TestFindRecord(t *testing.T) { + c := func(n int) record { return record{Kind: 'c', NewLine: n, File: "a.go"} } + a := func(n int) record { return record{Kind: 'a', NewLine: n, File: "a.go"} } + d := func(n, o int) record { return record{Kind: 'd', NewLine: n, OldLine: o, File: "a.go"} } + // Side-by-side: a modification is one row with d and a. + lines := []diffLine{ + row(record{Kind: 'f', File: "a.go"}), + row(record{Kind: 'h', NewLine: 1, File: "a.go"}), + row(c(1), c(1)), + row(d(2, 2), a(2)), + row(a(3)), + row(), + row(c(4), c(4)), + } + tests := []struct { + name string + want record + row int + }{ + {"deleted by old line", d(2, 2), 3}, + {"added on the right", a(3), 4}, + {"hunk", record{Kind: 'h', NewLine: 1, File: "a.go"}, 1}, + {"file", record{Kind: 'f', File: "a.go"}, 0}, + {"nearest following line", d(4, 7), 6}, + {"past the end", c(9), -1}, + {"other file", record{Kind: 'c', NewLine: 1, File: "b.go"}, -1}, + } + for _, tt := range tests { + if got := findRecord(lines, tt.want); got != tt.row { + t.Errorf("%s: expected row %d, got %d", tt.name, tt.row, got) + } + } +} + +func TestSetSideBySide_KeepsPosition(t *testing.T) { + m := newTestModel(t) + m.SetSize(80, 4) + c := func(n int) record { return record{Kind: 'c', NewLine: n, File: "a.go"} } + var unified, sbs []diffLine + for n := 1; n <= 20; n++ { + unified = append(unified, row(c(n))) + sbs = append(sbs, row(), row(c(n), c(n))) // a decoration row before every line + } + files := []*gitdiff.File{{}} + m.file = &cachedNode{path: "a.go", files: files} + m.cache[cacheKey("a.go", false)] = m.file + m.cache[cacheKey("a.go", true)] = &cachedNode{path: "a.go", files: files, diff: sbs} + m, _ = m.Update(diffContentMsg{cacheKey: cacheKey("a.go", false), node: m.file, lines: unified}) + m.ScrollDown(6) // line 7 at the top + + m.SetSideBySide(true) + if got := m.fvp.GetItemMetrics().FirstVisibleItemIdx; got != 13 { + t.Fatalf("expected row 13 (line 7) at the top, got %d", got) + } +} From 17254ceb2c413e49841f0a8628e3e7dbf9195694 Mon Sep 17 00:00:00 2001 From: Pablo Speciale Date: Sat, 14 Nov 2026 17:24:58 +0100 Subject: [PATCH 04/32] fix: take the scroll anchor before the viewport is resized Resizing first let the viewport clamp its top row to the old row count, so a taller pane near the bottom moved up. Also skip the anchor when no content row is visible. --- pkg/ui/panes/diffviewer/diffviewer.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/pkg/ui/panes/diffviewer/diffviewer.go b/pkg/ui/panes/diffviewer/diffviewer.go index 1a0ace7..191e5aa 100644 --- a/pkg/ui/panes/diffviewer/diffviewer.go +++ b/pkg/ui/panes/diffviewer/diffviewer.go @@ -260,11 +260,12 @@ func (m Model) View() string { } func (m *Model) SetSize(width, height int) tea.Cmd { + // Before resizing: the viewport clamps its top row to the new size. + m.keepPosition() m.Width = width m.Height = height m.fvp.SetWidth(m.contentWidth()) m.fvp.SetHeight(m.Height) - m.keepPosition() m.ClearCache() return m.diff() } @@ -289,6 +290,9 @@ func (m *Model) keepPosition() { if m.SelectionEnabled() { row = m.fvp.GetSelectedItemIdx() } + if row < 0 { + return + } // Keep a pending anchor if the current render hasn't arrived yet. if rec, ok := firstRecord(node.diff, row); ok { m.anchor = &rec From 3c5533e9fd8d3c97b67a901e20ffc2399cc90109 Mon Sep 17 00:00:00 2001 From: Pablo Speciale Date: Sat, 14 Nov 2026 17:25:50 +0100 Subject: [PATCH 05/32] fix: keep rows without a record in place when restoring the scroll Remember the top row's offset from the first row of its anchor record, so a preamble, delta's decoration rows and wrapped rows stay where they were instead of snapping to the record. --- pkg/ui/panes/diffviewer/diffviewer.go | 19 ++++++++++++++----- pkg/ui/panes/diffviewer/osc1717_test.go | 23 +++++++++++++++++++++++ 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/pkg/ui/panes/diffviewer/diffviewer.go b/pkg/ui/panes/diffviewer/diffviewer.go index 191e5aa..a2ff125 100644 --- a/pkg/ui/panes/diffviewer/diffviewer.go +++ b/pkg/ui/panes/diffviewer/diffviewer.go @@ -96,8 +96,14 @@ type Model struct { useUserDeltaTheme bool preamble string sb common.Scrollbar - // anchor is the diff line to scroll back to once the re-rendered diff is shown. - anchor *record + // anchor is where to scroll back to once the re-rendered diff is shown. + anchor *scrollAnchor +} + +// scrollAnchor is a diff line and how many rows below its first row the view was. +type scrollAnchor struct { + rec record + offset int } // SetPreamble stores the preamble text (e.g. commit metadata from git show). @@ -277,7 +283,8 @@ func (m *Model) UpdateTheme() tea.Cmd { } // keepPosition remembers the diff line at the top of the view (or the selected one), -// so the next render of this node scrolls back to it. +// so the next render of this node scrolls back to it. Rows without a record (a preamble, +// decorations, wrapped rows) are kept by their offset from the next record's first row. func (m *Model) keepPosition() { node := m.file if node == nil { @@ -295,7 +302,7 @@ func (m *Model) keepPosition() { } // Keep a pending anchor if the current render hasn't arrived yet. if rec, ok := firstRecord(node.diff, row); ok { - m.anchor = &rec + m.anchor = &scrollAnchor{rec: rec, offset: row - findRecord(node.diff, rec)} } } @@ -305,11 +312,13 @@ func (m *Model) setLines(lines []diffLine) { if m.anchor == nil { return } - row := findRecord(lines, *m.anchor) + row := findRecord(lines, m.anchor.rec) + offset := m.anchor.offset m.anchor = nil if row < 0 || m.fvp.GetMatchingItemsOnly() { return } + row = max(row+offset, 0) if m.SelectionEnabled() { m.fvp.SetSelectedItemIdx(row) return diff --git a/pkg/ui/panes/diffviewer/osc1717_test.go b/pkg/ui/panes/diffviewer/osc1717_test.go index 6f051f4..f88120e 100644 --- a/pkg/ui/panes/diffviewer/osc1717_test.go +++ b/pkg/ui/panes/diffviewer/osc1717_test.go @@ -151,3 +151,26 @@ func TestSetSideBySide_KeepsPosition(t *testing.T) { t.Fatalf("expected row 13 (line 7) at the top, got %d", got) } } + +func TestSetSideBySide_KeepsRecordlessTopRow(t *testing.T) { + c := func(n int) record { return record{Kind: 'c', NewLine: n, File: "a.go"} } + // A preamble, then line 1 wrapped over two rows. + lines := []diffLine{row(), row(), row(c(1)), row(c(1))} + for n := 2; n <= 20; n++ { + lines = append(lines, row(c(n))) + } + for _, top := range []int{0, 3} { + m := newTestModel(t) + m.SetSize(80, 4) + // A new file renders the same in both modes, so `s` re-shows the same lines. + m.file = &cachedNode{path: "a.go", files: []*gitdiff.File{{IsNew: true}}, diff: lines} + m.cache[cacheKey("a.go", false)] = m.file + m.fvp.SetObjects(lines) + m.ScrollDown(top) + + m.SetSideBySide(true) + if got := m.fvp.GetItemMetrics().FirstVisibleItemIdx; got != top { + t.Errorf("expected row %d to stay at the top, got %d", top, got) + } + } +} From f25396b671e53c66ff4a619a912137121c6ad7f0 Mon Sep 17 00:00:00 2001 From: Pablo Speciale Date: Sat, 14 Nov 2026 17:26:12 +0100 Subject: [PATCH 06/32] refactor: drop the nearest-line fallback and skip rows without records Re-renders show the same patch, so the exact record is always there. --- pkg/ui/panes/diffviewer/osc1717.go | 17 ++++++----------- pkg/ui/panes/diffviewer/osc1717_test.go | 1 - 2 files changed, 6 insertions(+), 12 deletions(-) diff --git a/pkg/ui/panes/diffviewer/osc1717.go b/pkg/ui/panes/diffviewer/osc1717.go index 0ef39da..6ccf765 100644 --- a/pkg/ui/panes/diffviewer/osc1717.go +++ b/pkg/ui/panes/diffviewer/osc1717.go @@ -43,6 +43,9 @@ func parseDeltaOutput(out string) []diffLine { // parseRecords removes the OSC 1717 sequences from a row and returns them. func parseRecords(row string) (string, []record) { + if !strings.Contains(row, osc1717Prefix) { + return row, nil + } var records []record var b strings.Builder for { @@ -86,24 +89,16 @@ func firstRecord(lines []diffLine, row int) (record, bool) { return record{}, false } -// findRecord returns the first row showing the same diff line as want, else the -// first row at or after its line in the same file, else -1. +// findRecord returns the first row showing the same diff line as want, or -1. func findRecord(lines []diffLine, want record) int { - nearest := -1 for i, l := range lines { for _, r := range l.records { - if r.File != want.File { - continue - } - if sameLine(r, want) { + if r.File == want.File && sameLine(r, want) { return i } - if nearest < 0 && want.Kind != 'f' && r.Kind != 'f' && r.NewLine >= want.NewLine { - nearest = i - } } } - return nearest + return -1 } // sameLine compares records of the same file: d by old line, c/a and h by new line. diff --git a/pkg/ui/panes/diffviewer/osc1717_test.go b/pkg/ui/panes/diffviewer/osc1717_test.go index f88120e..9fb628c 100644 --- a/pkg/ui/panes/diffviewer/osc1717_test.go +++ b/pkg/ui/panes/diffviewer/osc1717_test.go @@ -119,7 +119,6 @@ func TestFindRecord(t *testing.T) { {"added on the right", a(3), 4}, {"hunk", record{Kind: 'h', NewLine: 1, File: "a.go"}, 1}, {"file", record{Kind: 'f', File: "a.go"}, 0}, - {"nearest following line", d(4, 7), 6}, {"past the end", c(9), -1}, {"other file", record{Kind: 'c', NewLine: 1, File: "b.go"}, -1}, } From fe2ec61b995739ecfab363a7bf7f4b1bb01c260c Mon Sep 17 00:00:00 2001 From: Pablo Speciale Date: Sat, 14 Nov 2026 17:26:12 +0100 Subject: [PATCH 07/32] test: run the real delta without the user's git config --- pkg/ui/panes/diffviewer/osc1717_test.go | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/pkg/ui/panes/diffviewer/osc1717_test.go b/pkg/ui/panes/diffviewer/osc1717_test.go index 9fb628c..ff7bfbd 100644 --- a/pkg/ui/panes/diffviewer/osc1717_test.go +++ b/pkg/ui/panes/diffviewer/osc1717_test.go @@ -57,12 +57,10 @@ func TestParseDeltaOutput_RealDelta(t *testing.T) { if _, err := exec.LookPath("delta"); err != nil { t.Skip("delta not installed") } - t.Setenv("GIT_CONFIG_PARAMETERS", "") - t.Setenv("GIT_CONFIG_GLOBAL", "/dev/null") - t.Setenv("GIT_CONFIG_NOSYSTEM", "1") patch := "diff --git a/a;b.go b/a;b.go\n--- a/a;b.go\n+++ b/a;b.go\n" + "@@ -1,2 +1,2 @@\n ctx\n-old\n+new\n" - cmd := exec.Command("delta", "--paging=never", "--side-by-side", "-w=80") + t.Setenv("GIT_CONFIG_PARAMETERS", "") + cmd := exec.Command("delta", "--no-gitconfig", "--paging=never", "--side-by-side", "-w=80") cmd.Env = makeDeltaEnv(deltaOpts{}) cmd.Stdin = strings.NewReader(patch) out, err := cmd.Output() From 0f2c9b6e40085e5d8d791cfe0055c0c71fa4076f Mon Sep 17 00:00:00 2001 From: Pablo Speciale Date: Sat, 14 Nov 2026 18:01:54 +0100 Subject: [PATCH 08/32] fix: keep a wrapped-row offset within the anchor line's rows When the new layout wraps the anchor line over fewer rows, the offset spilled onto the next diff line. Rows above the anchor keep their offset. --- pkg/ui/panes/diffviewer/diffviewer.go | 13 ++++++++++--- pkg/ui/panes/diffviewer/osc1717.go | 16 ++++++++++++---- pkg/ui/panes/diffviewer/osc1717_test.go | 5 ++++- 3 files changed, 26 insertions(+), 8 deletions(-) diff --git a/pkg/ui/panes/diffviewer/diffviewer.go b/pkg/ui/panes/diffviewer/diffviewer.go index a2ff125..8da31c9 100644 --- a/pkg/ui/panes/diffviewer/diffviewer.go +++ b/pkg/ui/panes/diffviewer/diffviewer.go @@ -312,13 +312,20 @@ func (m *Model) setLines(lines []diffLine) { if m.anchor == nil { return } - row := findRecord(lines, m.anchor.rec) - offset := m.anchor.offset + a := *m.anchor m.anchor = nil + row := findRecord(lines, a.rec) if row < 0 || m.fvp.GetMatchingItemsOnly() { return } - row = max(row+offset, 0) + // Stay within the record's rows, so a wrapped row doesn't spill onto the next line. + for range a.offset { + if row+1 >= len(lines) || !lines[row+1].shows(a.rec) { + break + } + row++ + } + row = max(row+min(a.offset, 0), 0) if m.SelectionEnabled() { m.fvp.SetSelectedItemIdx(row) return diff --git a/pkg/ui/panes/diffviewer/osc1717.go b/pkg/ui/panes/diffviewer/osc1717.go index 6ccf765..61f55e6 100644 --- a/pkg/ui/panes/diffviewer/osc1717.go +++ b/pkg/ui/panes/diffviewer/osc1717.go @@ -92,15 +92,23 @@ func firstRecord(lines []diffLine, row int) (record, bool) { // findRecord returns the first row showing the same diff line as want, or -1. func findRecord(lines []diffLine, want record) int { for i, l := range lines { - for _, r := range l.records { - if r.File == want.File && sameLine(r, want) { - return i - } + if l.shows(want) { + return i } } return -1 } +// shows reports whether the row shows the same diff line as want. +func (o diffLine) shows(want record) bool { + for _, r := range o.records { + if r.File == want.File && sameLine(r, want) { + return true + } + } + return false +} + // sameLine compares records of the same file: d by old line, c/a and h by new line. func sameLine(r, want record) bool { switch want.Kind { diff --git a/pkg/ui/panes/diffviewer/osc1717_test.go b/pkg/ui/panes/diffviewer/osc1717_test.go index ff7bfbd..5362102 100644 --- a/pkg/ui/panes/diffviewer/osc1717_test.go +++ b/pkg/ui/panes/diffviewer/osc1717_test.go @@ -134,6 +134,9 @@ func TestSetSideBySide_KeepsPosition(t *testing.T) { var unified, sbs []diffLine for n := 1; n <= 20; n++ { unified = append(unified, row(c(n))) + if n == 7 { + unified = append(unified, row(c(n))) // line 7 wraps in unified only + } sbs = append(sbs, row(), row(c(n), c(n))) // a decoration row before every line } files := []*gitdiff.File{{}} @@ -141,7 +144,7 @@ func TestSetSideBySide_KeepsPosition(t *testing.T) { m.cache[cacheKey("a.go", false)] = m.file m.cache[cacheKey("a.go", true)] = &cachedNode{path: "a.go", files: files, diff: sbs} m, _ = m.Update(diffContentMsg{cacheKey: cacheKey("a.go", false), node: m.file, lines: unified}) - m.ScrollDown(6) // line 7 at the top + m.ScrollDown(7) // line 7's wrapped row at the top m.SetSideBySide(true) if got := m.fvp.GetItemMetrics().FirstVisibleItemIdx; got != 13 { From 71eb9b41adc99a67883e0b66a0567368be85254f Mon Sep 17 00:00:00 2001 From: Pablo Speciale Date: Sun, 15 Nov 2026 00:27:40 +0100 Subject: [PATCH 09/32] style: wrap a long test line for golines --- pkg/ui/panes/diffviewer/osc1717_test.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/pkg/ui/panes/diffviewer/osc1717_test.go b/pkg/ui/panes/diffviewer/osc1717_test.go index 5362102..562c6b7 100644 --- a/pkg/ui/panes/diffviewer/osc1717_test.go +++ b/pkg/ui/panes/diffviewer/osc1717_test.go @@ -28,7 +28,10 @@ func TestParseDeltaOutput(t *testing.T) { {{Kind: 'f', File: "a.go"}}, {{Kind: 'h', NewLine: 10, File: "a.go"}}, nil, - {{Kind: 'd', NewLine: 10, OldLine: 9, File: "a.go"}, {Kind: 'a', NewLine: 10, File: "a.go"}}, + { + {Kind: 'd', NewLine: 10, OldLine: 9, File: "a.go"}, + {Kind: 'a', NewLine: 10, File: "a.go"}, + }, {{Kind: 'c', NewLine: 11, File: "dir;b.go"}}, nil, // unknown type and version } From f0e7568c68a6a8b8781f268dfc104d01b73c8267 Mon Sep 17 00:00:00 2001 From: Pablo Speciale Date: Sun, 15 Nov 2026 11:23:57 +0100 Subject: [PATCH 10/32] fix: don't restore the scroll position after the user moved A scroll or jump made before the re-render arrives is no longer undone by the anchor taken at the s press or resize. --- pkg/ui/panes/diffviewer/diffviewer.go | 22 ++++++++++++++++++---- pkg/ui/panes/diffviewer/osc1717_test.go | 22 ++++++++++++++++++++++ 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/pkg/ui/panes/diffviewer/diffviewer.go b/pkg/ui/panes/diffviewer/diffviewer.go index 8da31c9..d627104 100644 --- a/pkg/ui/panes/diffviewer/diffviewer.go +++ b/pkg/ui/panes/diffviewer/diffviewer.go @@ -241,9 +241,14 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { } } + row := m.currentRow() fvp, fvpCmd := m.fvp.Update(msg) cmds = append(cmds, fvpCmd) m.fvp = fvp + // The user moved before the re-render arrived: don't scroll back. + if m.currentRow() != row { + m.anchor = nil + } return m, tea.Batch(cmds...) } @@ -293,10 +298,7 @@ func (m *Model) keepPosition() { if node == nil || m.fvp.GetMatchingItemsOnly() { return } - row := m.fvp.GetItemMetrics().FirstVisibleItemIdx - if m.SelectionEnabled() { - row = m.fvp.GetSelectedItemIdx() - } + row := m.currentRow() if row < 0 { return } @@ -306,6 +308,14 @@ func (m *Model) keepPosition() { } } +// currentRow is the selected row, or the top visible one without a selection. +func (m *Model) currentRow() int { + if m.SelectionEnabled() { + return m.fvp.GetSelectedItemIdx() + } + return m.fvp.GetItemMetrics().FirstVisibleItemIdx +} + // setLines shows lines and scrolls to the anchor, if any. func (m *Model) setLines(lines []diffLine) { m.fvp.SetObjects(lines) @@ -500,21 +510,25 @@ func (m *Model) SetSideBySide(sideBySide bool) tea.Cmd { // ScrollUp scrolls the viewport up by the given number of lines. func (m *Model) ScrollUp(lines int) { + m.anchor = nil m.fvp.ScrollUp(lines) } // ScrollDown scrolls the viewport down by the given number of lines. func (m *Model) ScrollDown(lines int) { + m.anchor = nil m.fvp.ScrollDown(lines) } // ScrollBottom scrolls the viewport to the bottom. func (m *Model) ScrollBottom() { + m.anchor = nil m.fvp.GoToBottom() } // ScrollTop scrolls the viewport to its top. func (m *Model) ScrollTop() { + m.anchor = nil m.fvp.GoToTop() } diff --git a/pkg/ui/panes/diffviewer/osc1717_test.go b/pkg/ui/panes/diffviewer/osc1717_test.go index 562c6b7..e1473c0 100644 --- a/pkg/ui/panes/diffviewer/osc1717_test.go +++ b/pkg/ui/panes/diffviewer/osc1717_test.go @@ -6,6 +6,7 @@ import ( "strings" "testing" + tea "charm.land/bubbletea/v2" "github.com/bluekeyes/go-gitdiff/gitdiff" "github.com/robinovitch61/viewport/viewport/item" ) @@ -177,3 +178,24 @@ func TestSetSideBySide_KeepsRecordlessTopRow(t *testing.T) { } } } + +func TestSetSideBySide_UserMoveDropsAnchor(t *testing.T) { + m := newTestModel(t) + m.SetSize(80, 4) + c := func(n int) record { return record{Kind: 'c', NewLine: n, File: "a.go"} } + var lines []diffLine + for n := 1; n <= 20; n++ { + lines = append(lines, row(c(n))) + } + m.file = &cachedNode{path: "a.go", files: []*gitdiff.File{{}}, diff: lines} + m.cache[cacheKey("a.go", false)] = m.file + m.fvp.SetObjects(lines) + m.ScrollDown(10) + + m.SetSideBySide(true) // renders async: the anchor is pending + m, _ = m.Update(tea.KeyPressMsg{Code: 'g', Text: "g"}) + m, _ = m.Update(diffContentMsg{cacheKey: cacheKey("a.go", true), node: m.file, lines: lines}) + if got := m.fvp.GetItemMetrics().FirstVisibleItemIdx; got != 0 { + t.Fatalf("expected g to keep the top, got row %d", got) + } +} From 654d4f5126a6f408cabb57a1c52483d6f7e7e780 Mon Sep 17 00:00:00 2001 From: Pablo Speciale Date: Sun, 15 Nov 2026 16:03:16 +0100 Subject: [PATCH 11/32] fix: keep the scroll anchor when a scroll call doesn't move ScrollUp/Down/Top/Bottom dropped the pending anchor even at the edge of the diff, where they don't move. They now share Update's check. --- pkg/ui/panes/diffviewer/diffviewer.go | 24 ++++++++++++++++-------- pkg/ui/panes/diffviewer/osc1717_test.go | 23 +++++++++++++++++++++++ 2 files changed, 39 insertions(+), 8 deletions(-) diff --git a/pkg/ui/panes/diffviewer/diffviewer.go b/pkg/ui/panes/diffviewer/diffviewer.go index d627104..19739ce 100644 --- a/pkg/ui/panes/diffviewer/diffviewer.go +++ b/pkg/ui/panes/diffviewer/diffviewer.go @@ -245,10 +245,7 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { fvp, fvpCmd := m.fvp.Update(msg) cmds = append(cmds, fvpCmd) m.fvp = fvp - // The user moved before the re-render arrived: don't scroll back. - if m.currentRow() != row { - m.anchor = nil - } + m.followMove(row) return m, tea.Batch(cmds...) } @@ -316,6 +313,13 @@ func (m *Model) currentRow() int { return m.fvp.GetItemMetrics().FirstVisibleItemIdx } +// followMove keeps a pending render from undoing a move the user made from row. +func (m *Model) followMove(row int) { + if m.currentRow() != row { + m.anchor = nil + } +} + // setLines shows lines and scrolls to the anchor, if any. func (m *Model) setLines(lines []diffLine) { m.fvp.SetObjects(lines) @@ -510,26 +514,30 @@ func (m *Model) SetSideBySide(sideBySide bool) tea.Cmd { // ScrollUp scrolls the viewport up by the given number of lines. func (m *Model) ScrollUp(lines int) { - m.anchor = nil + row := m.currentRow() m.fvp.ScrollUp(lines) + m.followMove(row) } // ScrollDown scrolls the viewport down by the given number of lines. func (m *Model) ScrollDown(lines int) { - m.anchor = nil + row := m.currentRow() m.fvp.ScrollDown(lines) + m.followMove(row) } // ScrollBottom scrolls the viewport to the bottom. func (m *Model) ScrollBottom() { - m.anchor = nil + row := m.currentRow() m.fvp.GoToBottom() + m.followMove(row) } // ScrollTop scrolls the viewport to its top. func (m *Model) ScrollTop() { - m.anchor = nil + row := m.currentRow() m.fvp.GoToTop() + m.followMove(row) } // ScrollLeft moves the viewport to the left by the given number of columns. diff --git a/pkg/ui/panes/diffviewer/osc1717_test.go b/pkg/ui/panes/diffviewer/osc1717_test.go index e1473c0..c518ae3 100644 --- a/pkg/ui/panes/diffviewer/osc1717_test.go +++ b/pkg/ui/panes/diffviewer/osc1717_test.go @@ -199,3 +199,26 @@ func TestSetSideBySide_UserMoveDropsAnchor(t *testing.T) { t.Fatalf("expected g to keep the top, got row %d", got) } } + +func TestSetSideBySide_WheelWithoutMoveKeepsAnchor(t *testing.T) { + m := newTestModel(t) + m.SetSize(80, 4) + c := func(n int) record { return record{Kind: 'c', NewLine: n, File: "a.go"} } + var unified, sbs []diffLine + for n := 1; n <= 20; n++ { + unified = append(unified, row(c(n))) + sbs = append(sbs, row(), row(c(n), c(n))) // a decoration row before every line + } + m.file = &cachedNode{path: "a.go", files: []*gitdiff.File{{}}, diff: unified} + m.cache[cacheKey("a.go", false)] = m.file + m.fvp.SetObjects(unified) + m.ScrollBottom() + want, _ := firstRecord(unified, m.fvp.GetItemMetrics().FirstVisibleItemIdx) + + m.SetSideBySide(true) + m.ScrollDown(3) // the wheel at the bottom doesn't move + m, _ = m.Update(diffContentMsg{cacheKey: cacheKey("a.go", true), node: m.file, lines: sbs}) + if got, _ := firstRecord(sbs, m.fvp.GetItemMetrics().FirstVisibleItemIdx); got != want { + t.Fatalf("expected line %d at the top, got line %d", want.NewLine, got.NewLine) + } +} From 67221b479ee0105f4efbc445c06175f61726ec5a Mon Sep 17 00:00:00 2001 From: Pablo Speciale Date: Sun, 15 Nov 2026 16:05:02 +0100 Subject: [PATCH 12/32] fix: follow a move made while the re-render is pending Scrolling right after s or a resize kept the row index on the new layout, so a relative move landed on another line. The viewer now keeps the lines on screen and re-anchors to the line the move lands on; g and G still go to the top and bottom. currentRecord gives the record of the current row from those lines. --- pkg/ui/panes/diffviewer/diffviewer.go | 109 ++++++++++++++++-------- pkg/ui/panes/diffviewer/osc1717_test.go | 45 ++++++---- 2 files changed, 102 insertions(+), 52 deletions(-) diff --git a/pkg/ui/panes/diffviewer/diffviewer.go b/pkg/ui/panes/diffviewer/diffviewer.go index 19739ce..4a9f4e0 100644 --- a/pkg/ui/panes/diffviewer/diffviewer.go +++ b/pkg/ui/panes/diffviewer/diffviewer.go @@ -96,16 +96,29 @@ type Model struct { useUserDeltaTheme bool preamble string sb common.Scrollbar + // shown are the lines on screen: the last render while a new one is pending. + shown []diffLine // anchor is where to scroll back to once the re-rendered diff is shown. anchor *scrollAnchor } -// scrollAnchor is a diff line and how many rows below its first row the view was. +// scrollAnchor is a diff line and how many rows below its first row the view was, +// or the top or bottom of the diff. type scrollAnchor struct { rec record offset int + edge move } +// move is how the user moved the view. +type move int + +const ( + moveBy move = iota + moveTop + moveBottom +) + // SetPreamble stores the preamble text (e.g. commit metadata from git show). func (m *Model) SetPreamble(preamble string) { m.preamble = preamble @@ -241,11 +254,19 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { } } + mv := moveBy + if k, ok := msg.(tea.KeyPressMsg); ok && !m.fvp.FilterFocused() { + if key.Matches(k, ViewportKeyMap.Top) { + mv = moveTop + } else if key.Matches(k, ViewportKeyMap.Bottom) { + mv = moveBottom + } + } row := m.currentRow() fvp, fvpCmd := m.fvp.Update(msg) cmds = append(cmds, fvpCmd) m.fvp = fvp - m.followMove(row) + m.followMove(row, mv) return m, tea.Batch(cmds...) } @@ -288,21 +309,20 @@ func (m *Model) UpdateTheme() tea.Cmd { // so the next render of this node scrolls back to it. Rows without a record (a preamble, // decorations, wrapped rows) are kept by their offset from the next record's first row. func (m *Model) keepPosition() { - node := m.file - if node == nil { - node = m.dir - } - if node == nil || m.fvp.GetMatchingItemsOnly() { - return + // Without a record, a pending anchor is kept. + if rec, ok := m.currentRecord(); ok { + m.anchor = &scrollAnchor{rec: rec, offset: m.currentRow() - findRecord(m.shown, rec)} } +} + +// currentRecord returns the first record at or below the current row of the lines on +// screen, so it is right while a new render is pending too. +func (m *Model) currentRecord() (record, bool) { row := m.currentRow() - if row < 0 { - return - } - // Keep a pending anchor if the current render hasn't arrived yet. - if rec, ok := firstRecord(node.diff, row); ok { - m.anchor = &scrollAnchor{rec: rec, offset: row - findRecord(node.diff, rec)} + if row < 0 || m.fvp.GetMatchingItemsOnly() { + return record{}, false } + return firstRecord(m.shown, row) } // currentRow is the selected row, or the top visible one without a selection. @@ -313,33 +333,52 @@ func (m *Model) currentRow() int { return m.fvp.GetItemMetrics().FirstVisibleItemIdx } -// followMove keeps a pending render from undoing a move the user made from row. -func (m *Model) followMove(row int) { - if m.currentRow() != row { - m.anchor = nil +// followMove keeps a pending render from undoing a move the user made from row: +// a jump to the top or bottom stays there, other moves keep the line they land on. +func (m *Model) followMove(row int, mv move) { + if m.anchor == nil || m.currentRow() == row { + return } + if mv != moveBy { + m.anchor = &scrollAnchor{edge: mv} + return + } + m.anchor = nil + m.keepPosition() +} + +// show puts lines on screen. +func (m *Model) show(lines []diffLine) { + m.shown = lines + m.fvp.SetObjects(lines) } // setLines shows lines and scrolls to the anchor, if any. func (m *Model) setLines(lines []diffLine) { - m.fvp.SetObjects(lines) + m.show(lines) if m.anchor == nil { return } a := *m.anchor m.anchor = nil - row := findRecord(lines, a.rec) - if row < 0 || m.fvp.GetMatchingItemsOnly() { - return - } - // Stay within the record's rows, so a wrapped row doesn't spill onto the next line. - for range a.offset { - if row+1 >= len(lines) || !lines[row+1].shows(a.rec) { - break + row := 0 + switch a.edge { + case moveBottom: + row = max(len(lines)-1, 0) + case moveBy: + row = findRecord(lines, a.rec) + if row < 0 || m.fvp.GetMatchingItemsOnly() { + return + } + // Stay within the record's rows, so a wrapped row doesn't spill onto the next line. + for range a.offset { + if row+1 >= len(lines) || !lines[row+1].shows(a.rec) { + break + } + row++ } - row++ + row = max(row+min(a.offset, 0), 0) } - row = max(row+min(a.offset, 0), 0) if m.SelectionEnabled() { m.fvp.SetSelectedItemIdx(row) return @@ -449,7 +488,7 @@ func (m Model) SetFilePatch(file *gitdiff.File) (Model, tea.Cmd) { if cached, ok := m.cache[key]; ok { m.file = cached m.updateHeader() - m.fvp.SetObjects(cached.diff) + m.show(cached.diff) return m, nil } @@ -476,7 +515,7 @@ func (m Model) SetDirPatch(dirPath string, files []*gitdiff.File) (Model, tea.Cm if cached, ok := m.cache[key]; ok { m.dir = cached m.updateHeader() - m.fvp.SetObjects(cached.diff) + m.show(cached.diff) return m, nil } @@ -516,28 +555,28 @@ func (m *Model) SetSideBySide(sideBySide bool) tea.Cmd { func (m *Model) ScrollUp(lines int) { row := m.currentRow() m.fvp.ScrollUp(lines) - m.followMove(row) + m.followMove(row, moveBy) } // ScrollDown scrolls the viewport down by the given number of lines. func (m *Model) ScrollDown(lines int) { row := m.currentRow() m.fvp.ScrollDown(lines) - m.followMove(row) + m.followMove(row, moveBy) } // ScrollBottom scrolls the viewport to the bottom. func (m *Model) ScrollBottom() { row := m.currentRow() m.fvp.GoToBottom() - m.followMove(row) + m.followMove(row, moveBottom) } // ScrollTop scrolls the viewport to its top. func (m *Model) ScrollTop() { row := m.currentRow() m.fvp.GoToTop() - m.followMove(row) + m.followMove(row, moveTop) } // ScrollLeft moves the viewport to the left by the given number of columns. diff --git a/pkg/ui/panes/diffviewer/osc1717_test.go b/pkg/ui/panes/diffviewer/osc1717_test.go index c518ae3..5c2f2e2 100644 --- a/pkg/ui/panes/diffviewer/osc1717_test.go +++ b/pkg/ui/panes/diffviewer/osc1717_test.go @@ -169,7 +169,7 @@ func TestSetSideBySide_KeepsRecordlessTopRow(t *testing.T) { // A new file renders the same in both modes, so `s` re-shows the same lines. m.file = &cachedNode{path: "a.go", files: []*gitdiff.File{{IsNew: true}}, diff: lines} m.cache[cacheKey("a.go", false)] = m.file - m.fvp.SetObjects(lines) + m.show(lines) m.ScrollDown(top) m.SetSideBySide(true) @@ -179,24 +179,35 @@ func TestSetSideBySide_KeepsRecordlessTopRow(t *testing.T) { } } -func TestSetSideBySide_UserMoveDropsAnchor(t *testing.T) { - m := newTestModel(t) - m.SetSize(80, 4) +func TestSetSideBySide_UserMoveDuringRender(t *testing.T) { c := func(n int) record { return record{Kind: 'c', NewLine: n, File: "a.go"} } - var lines []diffLine + var unified, sbs []diffLine for n := 1; n <= 20; n++ { - lines = append(lines, row(c(n))) + unified = append(unified, row(c(n))) + sbs = append(sbs, row(), row(c(n), c(n))) // a decoration row before every line } - m.file = &cachedNode{path: "a.go", files: []*gitdiff.File{{}}, diff: lines} - m.cache[cacheKey("a.go", false)] = m.file - m.fvp.SetObjects(lines) - m.ScrollDown(10) - - m.SetSideBySide(true) // renders async: the anchor is pending - m, _ = m.Update(tea.KeyPressMsg{Code: 'g', Text: "g"}) - m, _ = m.Update(diffContentMsg{cacheKey: cacheKey("a.go", true), node: m.file, lines: lines}) - if got := m.fvp.GetItemMetrics().FirstVisibleItemIdx; got != 0 { - t.Fatalf("expected g to keep the top, got row %d", got) + for _, key := range []string{"g", "G", "j"} { + m := newTestModel(t) + m.SetSize(80, 6) + m.file = &cachedNode{path: "a.go", files: []*gitdiff.File{{}}, diff: unified} + m.cache[cacheKey("a.go", false)] = m.file + m.show(unified) + m.ScrollDown(10) + + m.SetSideBySide(true) // renders async: the anchor is pending + m, _ = m.Update(tea.KeyPressMsg{Code: rune(key[0]), Text: key}) + want, _ := m.currentRecord() + m, _ = m.Update(diffContentMsg{cacheKey: cacheKey("a.go", true), node: m.file, lines: sbs}) + metrics := m.fvp.GetItemMetrics() + got, _ := firstRecord(sbs, metrics.FirstVisibleItemIdx) + switch { + case key == "g" && metrics.FirstVisibleItemIdx != 0: + t.Errorf("g: expected the top, got row %d", metrics.FirstVisibleItemIdx) + case key == "G" && metrics.LastVisibleItemIdx != len(sbs)-1: + t.Errorf("G: expected the bottom, got row %d", metrics.LastVisibleItemIdx) + case key == "j" && got != want: + t.Errorf("j: expected line %d at the top, got line %d", want.NewLine, got.NewLine) + } } } @@ -211,7 +222,7 @@ func TestSetSideBySide_WheelWithoutMoveKeepsAnchor(t *testing.T) { } m.file = &cachedNode{path: "a.go", files: []*gitdiff.File{{}}, diff: unified} m.cache[cacheKey("a.go", false)] = m.file - m.fvp.SetObjects(unified) + m.show(unified) m.ScrollBottom() want, _ := firstRecord(unified, m.fvp.GetItemMetrics().FirstVisibleItemIdx) From 6d05ccedbe28e457c38865f3b6a66640ce6aa23d Mon Sep 17 00:00:00 2001 From: Pablo Speciale Date: Sun, 15 Nov 2026 16:05:09 +0100 Subject: [PATCH 13/32] docs: say how rows without a record and wrapped rows are anchored --- pkg/ui/panes/diffviewer/diffviewer.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/pkg/ui/panes/diffviewer/diffviewer.go b/pkg/ui/panes/diffviewer/diffviewer.go index 4a9f4e0..175f4bc 100644 --- a/pkg/ui/panes/diffviewer/diffviewer.go +++ b/pkg/ui/panes/diffviewer/diffviewer.go @@ -102,8 +102,8 @@ type Model struct { anchor *scrollAnchor } -// scrollAnchor is a diff line and how many rows below its first row the view was, -// or the top or bottom of the diff. +// scrollAnchor is a diff line and the view's offset from its first row (negative for +// rows above it without a record), or the top or bottom of the diff. type scrollAnchor struct { rec record offset int @@ -307,7 +307,8 @@ func (m *Model) UpdateTheme() tea.Cmd { // keepPosition remembers the diff line at the top of the view (or the selected one), // so the next render of this node scrolls back to it. Rows without a record (a preamble, -// decorations, wrapped rows) are kept by their offset from the next record's first row. +// blank or decoration rows) keep a negative offset from the next record's first row; +// wrapped rows repeat their record and keep a positive offset, capped to the line's rows. func (m *Model) keepPosition() { // Without a record, a pending anchor is kept. if rec, ok := m.currentRecord(); ok { From 18286d9b9cd0020c81cfd67d274adbbd3d80261d Mon Sep 17 00:00:00 2001 From: Pablo Speciale Date: Sun, 15 Nov 2026 16:05:44 +0100 Subject: [PATCH 14/32] fix: unquote octal-escaped file names in OSC 1717 records Git quotes non-ASCII names with octal escapes and delta copies them into the record, so a.txt with an umlaut came through as \303\244.txt. --- pkg/ui/panes/diffviewer/osc1717.go | 9 ++++++++- pkg/ui/panes/diffviewer/osc1717_test.go | 12 ++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/pkg/ui/panes/diffviewer/osc1717.go b/pkg/ui/panes/diffviewer/osc1717.go index 61f55e6..69e77b1 100644 --- a/pkg/ui/panes/diffviewer/osc1717.go +++ b/pkg/ui/panes/diffviewer/osc1717.go @@ -76,7 +76,14 @@ func parseRecord(body string) (record, bool) { } newLine, _ := strconv.Atoi(fields[2]) oldLine, _ := strconv.Atoi(fields[3]) - return record{Kind: fields[1][0], NewLine: newLine, OldLine: oldLine, File: fields[4]}, true + file := fields[4] + // Git quotes unusual names with octal escapes (\303\244 for ä), and delta copies them. + if strings.Contains(file, `\`) { + if name, err := strconv.Unquote(`"` + file + `"`); err == nil { + file = name + } + } + return record{Kind: fields[1][0], NewLine: newLine, OldLine: oldLine, File: file}, true } // firstRecord returns the first record at or below row. diff --git a/pkg/ui/panes/diffviewer/osc1717_test.go b/pkg/ui/panes/diffviewer/osc1717_test.go index 5c2f2e2..11b955f 100644 --- a/pkg/ui/panes/diffviewer/osc1717_test.go +++ b/pkg/ui/panes/diffviewer/osc1717_test.go @@ -50,6 +50,18 @@ func TestParseRecords_StripsText(t *testing.T) { } } +func TestParseRecords_UnquotesFileName(t *testing.T) { + for raw, want := range map[string]string{ + `\303\244.txt`: "ä.txt", + `a\q.txt`: `a\q.txt`, // not a valid escape: kept as is + } { + _, records := parseRecords(osc("1;c;1;;"+raw) + "x") + if len(records) != 1 || records[0].File != want { + t.Errorf("%s: expected file %q, got %+v", raw, want, records) + } + } +} + func TestParseDeltaOutput_NoHandshake(t *testing.T) { lines := parseDeltaOutput("plain\n" + osc("1;c;1;;a.go") + " x") if len(lines) != 2 || lines[1].records != nil { From a98623cdff5f2f19145e4c55f64342d26517fc04 Mon Sep 17 00:00:00 2001 From: Pablo Speciale Date: Wed, 25 Nov 2026 23:30:46 +0100 Subject: [PATCH 15/32] fix: don't read records of the previous node while a new one renders --- pkg/ui/panes/diffviewer/diffviewer.go | 3 +++ pkg/ui/panes/diffviewer/osc1717_test.go | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/pkg/ui/panes/diffviewer/diffviewer.go b/pkg/ui/panes/diffviewer/diffviewer.go index 175f4bc..730afb6 100644 --- a/pkg/ui/panes/diffviewer/diffviewer.go +++ b/pkg/ui/panes/diffviewer/diffviewer.go @@ -503,6 +503,8 @@ func (m Model) SetFilePatch(file *gitdiff.File) (Model, tea.Cmd) { deletions: deletions, } m.cache[key] = m.file + // The old node's rows stay on screen until the render lands; they have no record for this one. + m.shown = nil m.updateHeader() return m, m.diffFile(m.file, m.contentWidth()) @@ -533,6 +535,7 @@ func (m Model) SetDirPatch(dirPath string, files []*gitdiff.File) (Model, tea.Cm deletions: deleted, } m.cache[key] = m.dir + m.shown = nil preamble := "" if dirPath == "/" { preamble = m.preamble diff --git a/pkg/ui/panes/diffviewer/osc1717_test.go b/pkg/ui/panes/diffviewer/osc1717_test.go index 11b955f..5026d1b 100644 --- a/pkg/ui/panes/diffviewer/osc1717_test.go +++ b/pkg/ui/panes/diffviewer/osc1717_test.go @@ -245,3 +245,21 @@ func TestSetSideBySide_WheelWithoutMoveKeepsAnchor(t *testing.T) { t.Fatalf("expected line %d at the top, got line %d", want.NewLine, got.NewLine) } } + +func TestSwitchToUncachedNode_HasNoRecord(t *testing.T) { + a := []diffLine{row(record{Kind: 'c', NewLine: 40, File: "a.go"})} + b := &gitdiff.File{OldName: "b.go", NewName: "b.go"} + switches := map[string]func(Model) Model{ + "file": func(m Model) Model { m, _ = m.SetFilePatch(b); return m }, + "dir": func(m Model) Model { m, _ = m.SetDirPatch("pkg", []*gitdiff.File{b}); return m }, + } + for name, switchTo := range switches { + m := newTestModel(t) + m.SetSize(80, 6) + m.show(a) + m = switchTo(m) + if rec, ok := m.currentRecord(); ok { + t.Errorf("%s: expected no record before the render lands, got %+v", name, rec) + } + } +} From f5520060a17fb1de499eacc6ca9fc63e44a8e2d8 Mon Sep 17 00:00:00 2001 From: Pablo Speciale Date: Wed, 25 Nov 2026 23:31:15 +0100 Subject: [PATCH 16/32] fix: unquote file names that keep git's quotes in OSC 1717 records --- pkg/ui/panes/diffviewer/osc1717.go | 9 +++++++-- pkg/ui/panes/diffviewer/osc1717_test.go | 5 +++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/pkg/ui/panes/diffviewer/osc1717.go b/pkg/ui/panes/diffviewer/osc1717.go index 69e77b1..e30e92c 100644 --- a/pkg/ui/panes/diffviewer/osc1717.go +++ b/pkg/ui/panes/diffviewer/osc1717.go @@ -77,9 +77,14 @@ func parseRecord(body string) (record, bool) { newLine, _ := strconv.Atoi(fields[2]) oldLine, _ := strconv.Atoi(fields[3]) file := fields[4] - // Git quotes unusual names with octal escapes (\303\244 for ä), and delta copies them. + // Git quotes unusual names with octal escapes (\303\244 for ä), and delta copies them, + // with the quotes for a renamed file. if strings.Contains(file, `\`) { - if name, err := strconv.Unquote(`"` + file + `"`); err == nil { + quoted := file + if len(file) < 2 || file[0] != '"' || file[len(file)-1] != '"' { + quoted = `"` + file + `"` + } + if name, err := strconv.Unquote(quoted); err == nil { file = name } } diff --git a/pkg/ui/panes/diffviewer/osc1717_test.go b/pkg/ui/panes/diffviewer/osc1717_test.go index 5026d1b..9d585d7 100644 --- a/pkg/ui/panes/diffviewer/osc1717_test.go +++ b/pkg/ui/panes/diffviewer/osc1717_test.go @@ -52,8 +52,9 @@ func TestParseRecords_StripsText(t *testing.T) { func TestParseRecords_UnquotesFileName(t *testing.T) { for raw, want := range map[string]string{ - `\303\244.txt`: "ä.txt", - `a\q.txt`: `a\q.txt`, // not a valid escape: kept as is + `\303\244.txt`: "ä.txt", + `"\303\244.txt"`: "ä.txt", // a rename keeps git's quotes + `a\q.txt`: `a\q.txt`, // not a valid escape: kept as is } { _, records := parseRecords(osc("1;c;1;;"+raw) + "x") if len(records) != 1 || records[0].File != want { From 51b689bb1fd6e1d43059e6b3d197ee124a05ecdc Mon Sep 17 00:00:00 2001 From: Pablo Speciale Date: Thu, 26 Nov 2026 13:31:47 +0100 Subject: [PATCH 17/32] refactor: compute the restored row in a pure anchorRow --- pkg/ui/panes/diffviewer/diffviewer.go | 46 +++++++++++++++++---------- 1 file changed, 29 insertions(+), 17 deletions(-) diff --git a/pkg/ui/panes/diffviewer/diffviewer.go b/pkg/ui/panes/diffviewer/diffviewer.go index 730afb6..186e5f6 100644 --- a/pkg/ui/panes/diffviewer/diffviewer.go +++ b/pkg/ui/panes/diffviewer/diffviewer.go @@ -362,23 +362,12 @@ func (m *Model) setLines(lines []diffLine) { } a := *m.anchor m.anchor = nil - row := 0 - switch a.edge { - case moveBottom: - row = max(len(lines)-1, 0) - case moveBy: - row = findRecord(lines, a.rec) - if row < 0 || m.fvp.GetMatchingItemsOnly() { - return - } - // Stay within the record's rows, so a wrapped row doesn't spill onto the next line. - for range a.offset { - if row+1 >= len(lines) || !lines[row+1].shows(a.rec) { - break - } - row++ - } - row = max(row+min(a.offset, 0), 0) + if a.edge == moveBy && m.fvp.GetMatchingItemsOnly() { + return + } + row, ok := anchorRow(lines, a) + if !ok { + return } if m.SelectionEnabled() { m.fvp.SetSelectedItemIdx(row) @@ -388,6 +377,29 @@ func (m *Model) setLines(lines []diffLine) { m.fvp.ScrollDown(row) } +// anchorRow returns the row of lines to scroll to for a, or false when its line is gone. +func anchorRow(lines []diffLine, a scrollAnchor) (int, bool) { + switch a.edge { + case moveTop: + return 0, true + case moveBottom: + return max(len(lines)-1, 0), true + } + row := findRecord(lines, a.rec) + if row < 0 { + return 0, false + } + if a.offset < 0 { + // A row above the line without a record, like a blank or decoration row. + return max(row+a.offset, 0), true + } + // A wrapped row: go down the line's rows, but not onto the next line. + for i := 0; i < a.offset && row+1 < len(lines) && lines[row+1].shows(a.rec); i++ { + row++ + } + return row, true +} + func (m Model) contentWidth() int { return m.Width - scrollbarWidth } From ed42303554f2d35d795cd693a8ff1e0b03318cc9 Mon Sep 17 00:00:00 2001 From: Pablo Speciale Date: Thu, 26 Nov 2026 13:32:03 +0100 Subject: [PATCH 18/32] refactor: track view moves in one place --- pkg/ui/panes/diffviewer/diffviewer.go | 28 ++++++++++----------------- 1 file changed, 10 insertions(+), 18 deletions(-) diff --git a/pkg/ui/panes/diffviewer/diffviewer.go b/pkg/ui/panes/diffviewer/diffviewer.go index 186e5f6..0613214 100644 --- a/pkg/ui/panes/diffviewer/diffviewer.go +++ b/pkg/ui/panes/diffviewer/diffviewer.go @@ -262,11 +262,9 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { mv = moveBottom } } - row := m.currentRow() - fvp, fvpCmd := m.fvp.Update(msg) + var fvpCmd tea.Cmd + m.tracked(mv, func() { m.fvp, fvpCmd = m.fvp.Update(msg) }) cmds = append(cmds, fvpCmd) - m.fvp = fvp - m.followMove(row, mv) return m, tea.Batch(cmds...) } @@ -334,9 +332,11 @@ func (m *Model) currentRow() int { return m.fvp.GetItemMetrics().FirstVisibleItemIdx } -// followMove keeps a pending render from undoing a move the user made from row: +// tracked runs moveView, a move the user made, so that a pending render doesn't undo it: // a jump to the top or bottom stays there, other moves keep the line they land on. -func (m *Model) followMove(row int, mv move) { +func (m *Model) tracked(mv move, moveView func()) { + row := m.currentRow() + moveView() if m.anchor == nil || m.currentRow() == row { return } @@ -569,30 +569,22 @@ func (m *Model) SetSideBySide(sideBySide bool) tea.Cmd { // ScrollUp scrolls the viewport up by the given number of lines. func (m *Model) ScrollUp(lines int) { - row := m.currentRow() - m.fvp.ScrollUp(lines) - m.followMove(row, moveBy) + m.tracked(moveBy, func() { m.fvp.ScrollUp(lines) }) } // ScrollDown scrolls the viewport down by the given number of lines. func (m *Model) ScrollDown(lines int) { - row := m.currentRow() - m.fvp.ScrollDown(lines) - m.followMove(row, moveBy) + m.tracked(moveBy, func() { m.fvp.ScrollDown(lines) }) } // ScrollBottom scrolls the viewport to the bottom. func (m *Model) ScrollBottom() { - row := m.currentRow() - m.fvp.GoToBottom() - m.followMove(row, moveBottom) + m.tracked(moveBottom, m.fvp.GoToBottom) } // ScrollTop scrolls the viewport to its top. func (m *Model) ScrollTop() { - row := m.currentRow() - m.fvp.GoToTop() - m.followMove(row, moveTop) + m.tracked(moveTop, m.fvp.GoToTop) } // ScrollLeft moves the viewport to the left by the given number of columns. From e674a5e863a7bda0f0287430ac62f62e9ccd62db Mon Sep 17 00:00:00 2001 From: Pablo Speciale Date: Thu, 26 Nov 2026 13:32:45 +0100 Subject: [PATCH 19/32] refactor: cut OSC 1717 sequences with strings.Cut and unquote names in a helper --- pkg/ui/panes/diffviewer/osc1717.go | 45 +++++++++++++++++------------- 1 file changed, 25 insertions(+), 20 deletions(-) diff --git a/pkg/ui/panes/diffviewer/osc1717.go b/pkg/ui/panes/diffviewer/osc1717.go index e30e92c..5577f37 100644 --- a/pkg/ui/panes/diffviewer/osc1717.go +++ b/pkg/ui/panes/diffviewer/osc1717.go @@ -49,19 +49,19 @@ func parseRecords(row string) (string, []record) { var records []record var b strings.Builder for { - start := strings.Index(row, osc1717Prefix) - if start < 0 { + before, after, ok := strings.Cut(row, osc1717Prefix) + if !ok { break } - end := strings.Index(row[start:], osc1717Term) - if end < 0 { - break + body, rest, ok := strings.Cut(after, osc1717Term) + if !ok { + break // unterminated: kept as text } - b.WriteString(row[:start]) - if r, ok := parseRecord(row[start+len(osc1717Prefix) : start+end]); ok { + b.WriteString(before) + if r, ok := parseRecord(body); ok { records = append(records, r) } - row = row[start+end+len(osc1717Term):] + row = rest } b.WriteString(row) return b.String(), records @@ -76,19 +76,24 @@ func parseRecord(body string) (record, bool) { } newLine, _ := strconv.Atoi(fields[2]) oldLine, _ := strconv.Atoi(fields[3]) - file := fields[4] - // Git quotes unusual names with octal escapes (\303\244 for ä), and delta copies them, - // with the quotes for a renamed file. - if strings.Contains(file, `\`) { - quoted := file - if len(file) < 2 || file[0] != '"' || file[len(file)-1] != '"' { - quoted = `"` + file + `"` - } - if name, err := strconv.Unquote(quoted); err == nil { - file = name - } + r := record{Kind: fields[1][0], NewLine: newLine, OldLine: oldLine, File: unquote(fields[4])} + return r, true +} + +// unquote undoes git's quoting of unusual file names (\303\244 for ä), which delta copies, +// with the quotes for a renamed file and without them otherwise. Invalid escapes stay as is. +func unquote(file string) string { + if !strings.Contains(file, `\`) { + return file + } + quoted := file + if len(file) < 2 || !strings.HasPrefix(file, `"`) || !strings.HasSuffix(file, `"`) { + quoted = `"` + file + `"` + } + if name, err := strconv.Unquote(quoted); err == nil { + return name } - return record{Kind: fields[1][0], NewLine: newLine, OldLine: oldLine, File: file}, true + return file } // firstRecord returns the first record at or below row. From 74166ba35152cc5f7b4da5743c4835fbe8ab3314 Mon Sep 17 00:00:00 2001 From: Pablo Speciale Date: Thu, 26 Nov 2026 13:33:21 +0100 Subject: [PATCH 20/32] test: share the line and model fixtures of the scroll tests --- pkg/ui/panes/diffviewer/osc1717_test.go | 68 +++++++++++++------------ 1 file changed, 35 insertions(+), 33 deletions(-) diff --git a/pkg/ui/panes/diffviewer/osc1717_test.go b/pkg/ui/panes/diffviewer/osc1717_test.go index 9d585d7..bdd0fde 100644 --- a/pkg/ui/panes/diffviewer/osc1717_test.go +++ b/pkg/ui/panes/diffviewer/osc1717_test.go @@ -111,19 +111,41 @@ func row(records ...record) diffLine { return diffLine{item: item.NewItem("x"), records: records} } +// ctxLine is a context line n of a.go. +func ctxLine(n int) record { return record{Kind: 'c', NewLine: n, File: "a.go"} } + +// unifiedAndSbs returns lines 1 to 20 of a.go in unified, and side by side with a +// decoration row before every line. +func unifiedAndSbs() (unified, sbs []diffLine) { + for n := 1; n <= 20; n++ { + unified = append(unified, row(ctxLine(n))) + sbs = append(sbs, row(), row(ctxLine(n), ctxLine(n))) + } + return unified, sbs +} + +// showing returns a model of the given height that shows lines as a.go in unified. +func showing(t *testing.T, height int, lines []diffLine) Model { + m := newTestModel(t) + m.SetSize(80, height) + m.file = &cachedNode{path: "a.go", files: []*gitdiff.File{{}}, diff: lines} + m.cache[cacheKey("a.go", false)] = m.file + m.show(lines) + return m +} + func TestFindRecord(t *testing.T) { - c := func(n int) record { return record{Kind: 'c', NewLine: n, File: "a.go"} } a := func(n int) record { return record{Kind: 'a', NewLine: n, File: "a.go"} } d := func(n, o int) record { return record{Kind: 'd', NewLine: n, OldLine: o, File: "a.go"} } // Side-by-side: a modification is one row with d and a. lines := []diffLine{ row(record{Kind: 'f', File: "a.go"}), row(record{Kind: 'h', NewLine: 1, File: "a.go"}), - row(c(1), c(1)), + row(ctxLine(1), ctxLine(1)), row(d(2, 2), a(2)), row(a(3)), row(), - row(c(4), c(4)), + row(ctxLine(4), ctxLine(4)), } tests := []struct { name string @@ -134,7 +156,7 @@ func TestFindRecord(t *testing.T) { {"added on the right", a(3), 4}, {"hunk", record{Kind: 'h', NewLine: 1, File: "a.go"}, 1}, {"file", record{Kind: 'f', File: "a.go"}, 0}, - {"past the end", c(9), -1}, + {"past the end", ctxLine(9), -1}, {"other file", record{Kind: 'c', NewLine: 1, File: "b.go"}, -1}, } for _, tt := range tests { @@ -147,14 +169,13 @@ func TestFindRecord(t *testing.T) { func TestSetSideBySide_KeepsPosition(t *testing.T) { m := newTestModel(t) m.SetSize(80, 4) - c := func(n int) record { return record{Kind: 'c', NewLine: n, File: "a.go"} } var unified, sbs []diffLine for n := 1; n <= 20; n++ { - unified = append(unified, row(c(n))) + unified = append(unified, row(ctxLine(n))) if n == 7 { - unified = append(unified, row(c(n))) // line 7 wraps in unified only + unified = append(unified, row(ctxLine(n))) // line 7 wraps in unified only } - sbs = append(sbs, row(), row(c(n), c(n))) // a decoration row before every line + sbs = append(sbs, row(), row(ctxLine(n), ctxLine(n))) // a decoration row before every line } files := []*gitdiff.File{{}} m.file = &cachedNode{path: "a.go", files: files} @@ -170,11 +191,10 @@ func TestSetSideBySide_KeepsPosition(t *testing.T) { } func TestSetSideBySide_KeepsRecordlessTopRow(t *testing.T) { - c := func(n int) record { return record{Kind: 'c', NewLine: n, File: "a.go"} } // A preamble, then line 1 wrapped over two rows. - lines := []diffLine{row(), row(), row(c(1)), row(c(1))} + lines := []diffLine{row(), row(), row(ctxLine(1)), row(ctxLine(1))} for n := 2; n <= 20; n++ { - lines = append(lines, row(c(n))) + lines = append(lines, row(ctxLine(n))) } for _, top := range []int{0, 3} { m := newTestModel(t) @@ -193,18 +213,9 @@ func TestSetSideBySide_KeepsRecordlessTopRow(t *testing.T) { } func TestSetSideBySide_UserMoveDuringRender(t *testing.T) { - c := func(n int) record { return record{Kind: 'c', NewLine: n, File: "a.go"} } - var unified, sbs []diffLine - for n := 1; n <= 20; n++ { - unified = append(unified, row(c(n))) - sbs = append(sbs, row(), row(c(n), c(n))) // a decoration row before every line - } + unified, sbs := unifiedAndSbs() for _, key := range []string{"g", "G", "j"} { - m := newTestModel(t) - m.SetSize(80, 6) - m.file = &cachedNode{path: "a.go", files: []*gitdiff.File{{}}, diff: unified} - m.cache[cacheKey("a.go", false)] = m.file - m.show(unified) + m := showing(t, 6, unified) m.ScrollDown(10) m.SetSideBySide(true) // renders async: the anchor is pending @@ -225,17 +236,8 @@ func TestSetSideBySide_UserMoveDuringRender(t *testing.T) { } func TestSetSideBySide_WheelWithoutMoveKeepsAnchor(t *testing.T) { - m := newTestModel(t) - m.SetSize(80, 4) - c := func(n int) record { return record{Kind: 'c', NewLine: n, File: "a.go"} } - var unified, sbs []diffLine - for n := 1; n <= 20; n++ { - unified = append(unified, row(c(n))) - sbs = append(sbs, row(), row(c(n), c(n))) // a decoration row before every line - } - m.file = &cachedNode{path: "a.go", files: []*gitdiff.File{{}}, diff: unified} - m.cache[cacheKey("a.go", false)] = m.file - m.show(unified) + unified, sbs := unifiedAndSbs() + m := showing(t, 4, unified) m.ScrollBottom() want, _ := firstRecord(unified, m.fvp.GetItemMetrics().FirstVisibleItemIdx) From e2250d98c48f29160a4c09ffac5567512f15019d Mon Sep 17 00:00:00 2001 From: Pablo Speciale Date: Thu, 26 Nov 2026 13:33:23 +0100 Subject: [PATCH 21/32] docs: leave the offset rules to anchorRow's comments --- pkg/ui/panes/diffviewer/diffviewer.go | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/pkg/ui/panes/diffviewer/diffviewer.go b/pkg/ui/panes/diffviewer/diffviewer.go index 0613214..eff1363 100644 --- a/pkg/ui/panes/diffviewer/diffviewer.go +++ b/pkg/ui/panes/diffviewer/diffviewer.go @@ -303,10 +303,8 @@ func (m *Model) UpdateTheme() tea.Cmd { return m.diff() } -// keepPosition remembers the diff line at the top of the view (or the selected one), -// so the next render of this node scrolls back to it. Rows without a record (a preamble, -// blank or decoration rows) keep a negative offset from the next record's first row; -// wrapped rows repeat their record and keep a positive offset, capped to the line's rows. +// keepPosition remembers the diff line at the top of the view (or the selected one) and +// the view's offset from its first row, so the next render scrolls back to it (anchorRow). func (m *Model) keepPosition() { // Without a record, a pending anchor is kept. if rec, ok := m.currentRecord(); ok { From 771a561f9dc01c16b9ea41d1f553cbed34add5ec Mon Sep 17 00:00:00 2001 From: Pablo Speciale Date: Thu, 26 Nov 2026 14:00:39 +0100 Subject: [PATCH 22/32] refactor: reanchor after moves without a closure, and jump to edges with the viewport Rename move to anchorEdge, merge show into setLines, reset anchor and shown together on a node switch, and give ScrollTop/ScrollBottom back their main bodies: nothing calls them while a render is pending. --- pkg/ui/panes/diffviewer/diffviewer.go | 110 ++++++++++++------------ pkg/ui/panes/diffviewer/osc1717_test.go | 8 +- 2 files changed, 60 insertions(+), 58 deletions(-) diff --git a/pkg/ui/panes/diffviewer/diffviewer.go b/pkg/ui/panes/diffviewer/diffviewer.go index eff1363..6ac1e37 100644 --- a/pkg/ui/panes/diffviewer/diffviewer.go +++ b/pkg/ui/panes/diffviewer/diffviewer.go @@ -102,21 +102,21 @@ type Model struct { anchor *scrollAnchor } -// scrollAnchor is a diff line and the view's offset from its first row (negative for -// rows above it without a record), or the top or bottom of the diff. +// scrollAnchor is where to scroll back to after a re-render: the top or bottom of the +// diff, or a diff line and the view's offset from its first row. type scrollAnchor struct { + edge anchorEdge rec record offset int - edge move } -// move is how the user moved the view. -type move int +// anchorEdge is the edge of the diff an anchor sticks to, if any. +type anchorEdge int const ( - moveBy move = iota - moveTop - moveBottom + edgeNone anchorEdge = iota + edgeTop + edgeBottom ) // SetPreamble stores the preamble text (e.g. commit metadata from git show). @@ -254,17 +254,19 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) { } } - mv := moveBy + edge := edgeNone if k, ok := msg.(tea.KeyPressMsg); ok && !m.fvp.FilterFocused() { if key.Matches(k, ViewportKeyMap.Top) { - mv = moveTop + edge = edgeTop } else if key.Matches(k, ViewportKeyMap.Bottom) { - mv = moveBottom + edge = edgeBottom } } - var fvpCmd tea.Cmd - m.tracked(mv, func() { m.fvp, fvpCmd = m.fvp.Update(msg) }) + row := m.currentRow() + fvp, fvpCmd := m.fvp.Update(msg) cmds = append(cmds, fvpCmd) + m.fvp = fvp + m.reanchor(row, edge) return m, tea.Batch(cmds...) } @@ -330,40 +332,41 @@ func (m *Model) currentRow() int { return m.fvp.GetItemMetrics().FirstVisibleItemIdx } -// tracked runs moveView, a move the user made, so that a pending render doesn't undo it: -// a jump to the top or bottom stays there, other moves keep the line they land on. -func (m *Model) tracked(mv move, moveView func()) { - row := m.currentRow() - moveView() +// reanchor keeps a pending render from undoing a move the user made from row: a jump to +// the top or bottom (edge) stays there, other moves keep the line they land on. +func (m *Model) reanchor(row int, edge anchorEdge) { if m.anchor == nil || m.currentRow() == row { return } - if mv != moveBy { - m.anchor = &scrollAnchor{edge: mv} + if edge != edgeNone { + m.anchor = &scrollAnchor{edge: edge} return } m.anchor = nil m.keepPosition() } -// show puts lines on screen. -func (m *Model) show(lines []diffLine) { +// setLines shows lines and scrolls to the pending anchor, if any. +func (m *Model) setLines(lines []diffLine) { m.shown = lines m.fvp.SetObjects(lines) -} - -// setLines shows lines and scrolls to the anchor, if any. -func (m *Model) setLines(lines []diffLine) { - m.show(lines) if m.anchor == nil { return } a := *m.anchor m.anchor = nil - if a.edge == moveBy && m.fvp.GetMatchingItemsOnly() { + switch a.edge { + case edgeTop: + m.fvp.GoToTop() + return + case edgeBottom: + m.fvp.GoToBottom() + return + } + if m.fvp.GetMatchingItemsOnly() { return } - row, ok := anchorRow(lines, a) + row, ok := anchorRow(lines, a.rec, a.offset) if !ok { return } @@ -375,24 +378,21 @@ func (m *Model) setLines(lines []diffLine) { m.fvp.ScrollDown(row) } -// anchorRow returns the row of lines to scroll to for a, or false when its line is gone. -func anchorRow(lines []diffLine, a scrollAnchor) (int, bool) { - switch a.edge { - case moveTop: - return 0, true - case moveBottom: - return max(len(lines)-1, 0), true - } - row := findRecord(lines, a.rec) +// anchorRow returns the row offset rows from rec's first row, or false when rec is gone. +// Rows above it (offset < 0) have no record, like blank or decoration rows. Rows below it +// are its wrapped rows, so it stops at the line's last row. +func anchorRow(lines []diffLine, rec record, offset int) (int, bool) { + row := findRecord(lines, rec) if row < 0 { return 0, false } - if a.offset < 0 { - // A row above the line without a record, like a blank or decoration row. - return max(row+a.offset, 0), true + if offset < 0 { + return max(row+offset, 0), true } - // A wrapped row: go down the line's rows, but not onto the next line. - for i := 0; i < a.offset && row+1 < len(lines) && lines[row+1].shows(a.rec); i++ { + for range offset { + if row+1 == len(lines) || !lines[row+1].shows(rec) { + break + } row++ } return row, true @@ -491,7 +491,8 @@ func (m Model) dirHeaderView() string { func (m Model) SetFilePatch(file *gitdiff.File) (Model, tea.Cmd) { m.dir = nil - m.anchor = nil + // The rows on screen are another node's until this one is shown. + m.anchor, m.shown = nil, nil fname := filenode.GetFileName(file) sideBySide := m.sideBySide && !file.IsNew && !file.IsDelete @@ -499,7 +500,7 @@ func (m Model) SetFilePatch(file *gitdiff.File) (Model, tea.Cmd) { if cached, ok := m.cache[key]; ok { m.file = cached m.updateHeader() - m.show(cached.diff) + m.setLines(cached.diff) return m, nil } @@ -513,8 +514,6 @@ func (m Model) SetFilePatch(file *gitdiff.File) (Model, tea.Cmd) { deletions: deletions, } m.cache[key] = m.file - // The old node's rows stay on screen until the render lands; they have no record for this one. - m.shown = nil m.updateHeader() return m, m.diffFile(m.file, m.contentWidth()) @@ -522,13 +521,13 @@ func (m Model) SetFilePatch(file *gitdiff.File) (Model, tea.Cmd) { func (m Model) SetDirPatch(dirPath string, files []*gitdiff.File) (Model, tea.Cmd) { m.file = nil - m.anchor = nil + m.anchor, m.shown = nil, nil key := cacheKey(dirPath, m.sideBySide) if cached, ok := m.cache[key]; ok { m.dir = cached m.updateHeader() - m.show(cached.diff) + m.setLines(cached.diff) return m, nil } @@ -545,7 +544,6 @@ func (m Model) SetDirPatch(dirPath string, files []*gitdiff.File) (Model, tea.Cm deletions: deleted, } m.cache[key] = m.dir - m.shown = nil preamble := "" if dirPath == "/" { preamble = m.preamble @@ -567,22 +565,26 @@ func (m *Model) SetSideBySide(sideBySide bool) tea.Cmd { // ScrollUp scrolls the viewport up by the given number of lines. func (m *Model) ScrollUp(lines int) { - m.tracked(moveBy, func() { m.fvp.ScrollUp(lines) }) + row := m.currentRow() + m.fvp.ScrollUp(lines) + m.reanchor(row, edgeNone) } // ScrollDown scrolls the viewport down by the given number of lines. func (m *Model) ScrollDown(lines int) { - m.tracked(moveBy, func() { m.fvp.ScrollDown(lines) }) + row := m.currentRow() + m.fvp.ScrollDown(lines) + m.reanchor(row, edgeNone) } // ScrollBottom scrolls the viewport to the bottom. func (m *Model) ScrollBottom() { - m.tracked(moveBottom, m.fvp.GoToBottom) + m.fvp.GoToBottom() } // ScrollTop scrolls the viewport to its top. func (m *Model) ScrollTop() { - m.tracked(moveTop, m.fvp.GoToTop) + m.fvp.GoToTop() } // ScrollLeft moves the viewport to the left by the given number of columns. diff --git a/pkg/ui/panes/diffviewer/osc1717_test.go b/pkg/ui/panes/diffviewer/osc1717_test.go index bdd0fde..aaf8c1f 100644 --- a/pkg/ui/panes/diffviewer/osc1717_test.go +++ b/pkg/ui/panes/diffviewer/osc1717_test.go @@ -130,7 +130,7 @@ func showing(t *testing.T, height int, lines []diffLine) Model { m.SetSize(80, height) m.file = &cachedNode{path: "a.go", files: []*gitdiff.File{{}}, diff: lines} m.cache[cacheKey("a.go", false)] = m.file - m.show(lines) + m.setLines(lines) return m } @@ -202,7 +202,7 @@ func TestSetSideBySide_KeepsRecordlessTopRow(t *testing.T) { // A new file renders the same in both modes, so `s` re-shows the same lines. m.file = &cachedNode{path: "a.go", files: []*gitdiff.File{{IsNew: true}}, diff: lines} m.cache[cacheKey("a.go", false)] = m.file - m.show(lines) + m.setLines(lines) m.ScrollDown(top) m.SetSideBySide(true) @@ -238,7 +238,7 @@ func TestSetSideBySide_UserMoveDuringRender(t *testing.T) { func TestSetSideBySide_WheelWithoutMoveKeepsAnchor(t *testing.T) { unified, sbs := unifiedAndSbs() m := showing(t, 4, unified) - m.ScrollBottom() + m.fvp.GoToBottom() want, _ := firstRecord(unified, m.fvp.GetItemMetrics().FirstVisibleItemIdx) m.SetSideBySide(true) @@ -259,7 +259,7 @@ func TestSwitchToUncachedNode_HasNoRecord(t *testing.T) { for name, switchTo := range switches { m := newTestModel(t) m.SetSize(80, 6) - m.show(a) + m.setLines(a) m = switchTo(m) if rec, ok := m.currentRecord(); ok { t.Errorf("%s: expected no record before the render lands, got %+v", name, rec) From 1cf712e4321d780fd585f5b7648e4ef2431756f0 Mon Sep 17 00:00:00 2001 From: Pablo Speciale Date: Thu, 26 Nov 2026 14:01:05 +0100 Subject: [PATCH 23/32] fix: keep g/G pressed at the edge while a re-render is pending --- pkg/ui/panes/diffviewer/diffviewer.go | 5 ++++- pkg/ui/panes/diffviewer/osc1717_test.go | 21 +++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/pkg/ui/panes/diffviewer/diffviewer.go b/pkg/ui/panes/diffviewer/diffviewer.go index 6ac1e37..d53c0a1 100644 --- a/pkg/ui/panes/diffviewer/diffviewer.go +++ b/pkg/ui/panes/diffviewer/diffviewer.go @@ -335,13 +335,16 @@ func (m *Model) currentRow() int { // reanchor keeps a pending render from undoing a move the user made from row: a jump to // the top or bottom (edge) stays there, other moves keep the line they land on. func (m *Model) reanchor(row int, edge anchorEdge) { - if m.anchor == nil || m.currentRow() == row { + if m.anchor == nil { return } if edge != edgeNone { m.anchor = &scrollAnchor{edge: edge} return } + if m.currentRow() == row { + return + } m.anchor = nil m.keepPosition() } diff --git a/pkg/ui/panes/diffviewer/osc1717_test.go b/pkg/ui/panes/diffviewer/osc1717_test.go index aaf8c1f..e1bccec 100644 --- a/pkg/ui/panes/diffviewer/osc1717_test.go +++ b/pkg/ui/panes/diffviewer/osc1717_test.go @@ -266,3 +266,24 @@ func TestSwitchToUncachedNode_HasNoRecord(t *testing.T) { } } } + +func TestSetSideBySide_EdgeKeyAtTheEdge(t *testing.T) { + unified, sbs := unifiedAndSbs() + for _, key := range []string{"g", "G"} { + m := showing(t, 4, unified) + if key == "G" { + m.fvp.GoToBottom() + } + + m.SetSideBySide(true) + m, _ = m.Update(tea.KeyPressMsg{Code: rune(key[0]), Text: key}) // already there + m, _ = m.Update(diffContentMsg{cacheKey: cacheKey("a.go", true), node: m.file, lines: sbs}) + metrics := m.fvp.GetItemMetrics() + if key == "g" && metrics.FirstVisibleItemIdx != 0 { + t.Errorf("g: expected the top, got row %d", metrics.FirstVisibleItemIdx) + } + if key == "G" && metrics.LastVisibleItemIdx != len(sbs)-1 { + t.Errorf("G: expected the bottom, got row %d", metrics.LastVisibleItemIdx) + } + } +} From 192118674c5f131b36c3c04738eca00bc673f2f9 Mon Sep 17 00:00:00 2001 From: Pablo Speciale Date: Thu, 26 Nov 2026 14:01:15 +0100 Subject: [PATCH 24/32] fix: don't overwrite a pending anchor when another re-render starts --- pkg/ui/panes/diffviewer/diffviewer.go | 6 +++++- pkg/ui/panes/diffviewer/osc1717_test.go | 14 ++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/pkg/ui/panes/diffviewer/diffviewer.go b/pkg/ui/panes/diffviewer/diffviewer.go index d53c0a1..fb3f268 100644 --- a/pkg/ui/panes/diffviewer/diffviewer.go +++ b/pkg/ui/panes/diffviewer/diffviewer.go @@ -308,7 +308,11 @@ func (m *Model) UpdateTheme() tea.Cmd { // keepPosition remembers the diff line at the top of the view (or the selected one) and // the view's offset from its first row, so the next render scrolls back to it (anchorRow). func (m *Model) keepPosition() { - // Without a record, a pending anchor is kept. + // A pending anchor still holds: the view can't have moved since without a reanchor, + // and a resize may already have clamped it. + if m.anchor != nil { + return + } if rec, ok := m.currentRecord(); ok { m.anchor = &scrollAnchor{rec: rec, offset: m.currentRow() - findRecord(m.shown, rec)} } diff --git a/pkg/ui/panes/diffviewer/osc1717_test.go b/pkg/ui/panes/diffviewer/osc1717_test.go index e1bccec..0b5dcd4 100644 --- a/pkg/ui/panes/diffviewer/osc1717_test.go +++ b/pkg/ui/panes/diffviewer/osc1717_test.go @@ -287,3 +287,17 @@ func TestSetSideBySide_EdgeKeyAtTheEdge(t *testing.T) { } } } + +func TestSetSideBySide_ResizeDuringRenderKeepsAnchor(t *testing.T) { + unified, sbs := unifiedAndSbs() + m := showing(t, 6, unified) + m.ScrollDown(10) + + m.SetSideBySide(true) + m, _ = m.Update(tea.KeyPressMsg{Code: 'G', Text: "G"}) + m.SetSize(81, 6) // a resize before the render lands + m, _ = m.Update(diffContentMsg{cacheKey: cacheKey("a.go", true), node: m.file, lines: sbs}) + if got := m.fvp.GetItemMetrics().LastVisibleItemIdx; got != len(sbs)-1 { + t.Fatalf("expected the bottom, got row %d", got) + } +} From b95383b2a50a0e766fb5c365216666a2903c6936 Mon Sep 17 00:00:00 2001 From: Pablo Speciale Date: Thu, 26 Nov 2026 14:01:41 +0100 Subject: [PATCH 25/32] refactor: match records with slices helpers and check the file in sameLine --- pkg/ui/panes/diffviewer/osc1717.go | 23 +++++++++-------------- 1 file changed, 9 insertions(+), 14 deletions(-) diff --git a/pkg/ui/panes/diffviewer/osc1717.go b/pkg/ui/panes/diffviewer/osc1717.go index 5577f37..d72172e 100644 --- a/pkg/ui/panes/diffviewer/osc1717.go +++ b/pkg/ui/panes/diffviewer/osc1717.go @@ -1,6 +1,7 @@ package diffviewer import ( + "slices" "strconv" "strings" @@ -87,7 +88,7 @@ func unquote(file string) string { return file } quoted := file - if len(file) < 2 || !strings.HasPrefix(file, `"`) || !strings.HasSuffix(file, `"`) { + if !strings.HasPrefix(file, `"`) { quoted = `"` + file + `"` } if name, err := strconv.Unquote(quoted); err == nil { @@ -108,26 +109,20 @@ func firstRecord(lines []diffLine, row int) (record, bool) { // findRecord returns the first row showing the same diff line as want, or -1. func findRecord(lines []diffLine, want record) int { - for i, l := range lines { - if l.shows(want) { - return i - } - } - return -1 + return slices.IndexFunc(lines, func(l diffLine) bool { return l.shows(want) }) } // shows reports whether the row shows the same diff line as want. func (o diffLine) shows(want record) bool { - for _, r := range o.records { - if r.File == want.File && sameLine(r, want) { - return true - } - } - return false + return slices.ContainsFunc(o.records, func(r record) bool { return sameLine(r, want) }) } -// sameLine compares records of the same file: d by old line, c/a and h by new line. +// sameLine reports whether r is the same diff line as want: in the same file, d by old line, +// c and a by new line, f and h by kind and new line. func sameLine(r, want record) bool { + if r.File != want.File { + return false + } switch want.Kind { case 'd': return r.Kind == 'd' && r.OldLine == want.OldLine From 45ab706df45b7ff6150b26dea9d8907d6a879960 Mon Sep 17 00:00:00 2001 From: Pablo Speciale Date: Thu, 26 Nov 2026 14:02:59 +0100 Subject: [PATCH 26/32] test: test anchorRow, and sharpen and share the scroll test fixtures --- pkg/ui/panes/diffviewer/osc1717_test.go | 91 +++++++++++++------------ 1 file changed, 48 insertions(+), 43 deletions(-) diff --git a/pkg/ui/panes/diffviewer/osc1717_test.go b/pkg/ui/panes/diffviewer/osc1717_test.go index 0b5dcd4..dad2f98 100644 --- a/pkg/ui/panes/diffviewer/osc1717_test.go +++ b/pkg/ui/panes/diffviewer/osc1717_test.go @@ -3,6 +3,7 @@ package diffviewer import ( "os/exec" "reflect" + "slices" "strings" "testing" @@ -41,12 +42,8 @@ func TestParseDeltaOutput(t *testing.T) { t.Errorf("row %d: expected %+v, got %+v", i, want[i], l.records) } } -} - -func TestParseRecords_StripsText(t *testing.T) { - text, _ := parseRecords(osc("1;d;10;9;a.go") + "\x1b[31m-x" + osc("1;a;10;;a.go") + "+y") - if text != "\x1b[31m-x+y" { - t.Fatalf("expected records stripped, got %q", text) + if got := lines[3].item.Content(); got != "\x1b[31m-x+y" { + t.Errorf("expected the records stripped from the text, got %q", got) } } @@ -126,6 +123,7 @@ func unifiedAndSbs() (unified, sbs []diffLine) { // showing returns a model of the given height that shows lines as a.go in unified. func showing(t *testing.T, height int, lines []diffLine) Model { + t.Helper() m := newTestModel(t) m.SetSize(80, height) m.file = &cachedNode{path: "a.go", files: []*gitdiff.File{{}}, diff: lines} @@ -152,8 +150,10 @@ func TestFindRecord(t *testing.T) { want record row int }{ - {"deleted by old line", d(2, 2), 3}, - {"added on the right", a(3), 4}, + {"deleted by old line", d(99, 2), 3}, + {"deleted, other old line", d(2, 99), -1}, + {"added on the right of a row", a(2), 3}, + {"added", a(3), 4}, {"hunk", record{Kind: 'h', NewLine: 1, File: "a.go"}, 1}, {"file", record{Kind: 'f', File: "a.go"}, 0}, {"past the end", ctxLine(9), -1}, @@ -167,21 +167,10 @@ func TestFindRecord(t *testing.T) { } func TestSetSideBySide_KeepsPosition(t *testing.T) { - m := newTestModel(t) - m.SetSize(80, 4) - var unified, sbs []diffLine - for n := 1; n <= 20; n++ { - unified = append(unified, row(ctxLine(n))) - if n == 7 { - unified = append(unified, row(ctxLine(n))) // line 7 wraps in unified only - } - sbs = append(sbs, row(), row(ctxLine(n), ctxLine(n))) // a decoration row before every line - } - files := []*gitdiff.File{{}} - m.file = &cachedNode{path: "a.go", files: files} - m.cache[cacheKey("a.go", false)] = m.file - m.cache[cacheKey("a.go", true)] = &cachedNode{path: "a.go", files: files, diff: sbs} - m, _ = m.Update(diffContentMsg{cacheKey: cacheKey("a.go", false), node: m.file, lines: unified}) + unified, sbs := unifiedAndSbs() + unified = slices.Insert(unified, 7, row(ctxLine(7))) // line 7 wraps in unified only + m := showing(t, 4, unified) + m.cache[cacheKey("a.go", true)] = &cachedNode{path: "a.go", files: m.file.files, diff: sbs} m.ScrollDown(7) // line 7's wrapped row at the top m.SetSideBySide(true) @@ -191,24 +180,16 @@ func TestSetSideBySide_KeepsPosition(t *testing.T) { } func TestSetSideBySide_KeepsRecordlessTopRow(t *testing.T) { - // A preamble, then line 1 wrapped over two rows. - lines := []diffLine{row(), row(), row(ctxLine(1)), row(ctxLine(1))} - for n := 2; n <= 20; n++ { - lines = append(lines, row(ctxLine(n))) - } - for _, top := range []int{0, 3} { - m := newTestModel(t) - m.SetSize(80, 4) - // A new file renders the same in both modes, so `s` re-shows the same lines. - m.file = &cachedNode{path: "a.go", files: []*gitdiff.File{{IsNew: true}}, diff: lines} - m.cache[cacheKey("a.go", false)] = m.file - m.setLines(lines) - m.ScrollDown(top) + unified, _ := unifiedAndSbs() + lines := append([]diffLine{row(), row()}, unified...) // a two-row preamble + m := showing(t, 4, lines) + // A new file renders the same in both modes, so `s` re-shows the same lines. + m.file.files[0].IsNew = true + m.ScrollDown(1) // the preamble's second row at the top - m.SetSideBySide(true) - if got := m.fvp.GetItemMetrics().FirstVisibleItemIdx; got != top { - t.Errorf("expected row %d to stay at the top, got %d", top, got) - } + m.SetSideBySide(true) + if got := m.fvp.GetItemMetrics().FirstVisibleItemIdx; got != 1 { + t.Fatalf("expected row 1 to stay at the top, got %d", got) } } @@ -220,7 +201,6 @@ func TestSetSideBySide_UserMoveDuringRender(t *testing.T) { m.SetSideBySide(true) // renders async: the anchor is pending m, _ = m.Update(tea.KeyPressMsg{Code: rune(key[0]), Text: key}) - want, _ := m.currentRecord() m, _ = m.Update(diffContentMsg{cacheKey: cacheKey("a.go", true), node: m.file, lines: sbs}) metrics := m.fvp.GetItemMetrics() got, _ := firstRecord(sbs, metrics.FirstVisibleItemIdx) @@ -229,8 +209,8 @@ func TestSetSideBySide_UserMoveDuringRender(t *testing.T) { t.Errorf("g: expected the top, got row %d", metrics.FirstVisibleItemIdx) case key == "G" && metrics.LastVisibleItemIdx != len(sbs)-1: t.Errorf("G: expected the bottom, got row %d", metrics.LastVisibleItemIdx) - case key == "j" && got != want: - t.Errorf("j: expected line %d at the top, got line %d", want.NewLine, got.NewLine) + case key == "j" && got != ctxLine(12): + t.Errorf("j: expected line 12 at the top, got line %d", got.NewLine) } } } @@ -301,3 +281,28 @@ func TestSetSideBySide_ResizeDuringRenderKeepsAnchor(t *testing.T) { t.Fatalf("expected the bottom, got row %d", got) } } + +func TestAnchorRow(t *testing.T) { + // A row without a record, line 1 wrapped over two rows, then line 2. + lines := []diffLine{row(), row(ctxLine(1)), row(ctxLine(1)), row(ctxLine(2))} + tests := []struct { + name string + rec record + offset int + row int + ok bool + }{ + {"on the line", ctxLine(1), 0, 1, true}, + {"a row above it", ctxLine(1), -1, 0, true}, + {"above the first row", ctxLine(1), -5, 0, true}, + {"its wrapped row", ctxLine(1), 1, 2, true}, + {"not onto the next line", ctxLine(1), 5, 2, true}, + {"not past the last row", ctxLine(2), 3, 3, true}, + {"gone", ctxLine(9), 0, 0, false}, + } + for _, tt := range tests { + if row, ok := anchorRow(lines, tt.rec, tt.offset); row != tt.row || ok != tt.ok { + t.Errorf("%s: expected row %d (%v), got %d (%v)", tt.name, tt.row, tt.ok, row, ok) + } + } +} From e1bda731db819772f2c63cc2a400861fdf2dcbdd Mon Sep 17 00:00:00 2001 From: Pablo Speciale Date: Thu, 26 Nov 2026 21:59:50 +0100 Subject: [PATCH 27/32] test: keep the line scrolled to with the wheel during a pending render --- pkg/ui/panes/diffviewer/osc1717_test.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/pkg/ui/panes/diffviewer/osc1717_test.go b/pkg/ui/panes/diffviewer/osc1717_test.go index dad2f98..246353e 100644 --- a/pkg/ui/panes/diffviewer/osc1717_test.go +++ b/pkg/ui/panes/diffviewer/osc1717_test.go @@ -229,6 +229,20 @@ func TestSetSideBySide_WheelWithoutMoveKeepsAnchor(t *testing.T) { } } +func TestSetSideBySide_WheelDuringRender(t *testing.T) { + unified, sbs := unifiedAndSbs() + m := showing(t, 6, unified) + m.ScrollDown(5) + + m.SetSideBySide(true) // renders async: the anchor is pending + m.ScrollDown(3) // the wheel moves the old render + m, _ = m.Update(diffContentMsg{cacheKey: cacheKey("a.go", true), node: m.file, lines: sbs}) + + if got, _ := firstRecord(sbs, m.fvp.GetItemMetrics().FirstVisibleItemIdx); got != ctxLine(9) { + t.Fatalf("expected line 9 at the top, got line %d", got.NewLine) + } +} + func TestSwitchToUncachedNode_HasNoRecord(t *testing.T) { a := []diffLine{row(record{Kind: 'c', NewLine: 40, File: "a.go"})} b := &gitdiff.File{OldName: "b.go", NewName: "b.go"} From 0778ecf187a51fcb994483ff1d11120f37c5d72c Mon Sep 17 00:00:00 2001 From: Pablo Speciale Date: Thu, 26 Nov 2026 22:20:38 +0100 Subject: [PATCH 28/32] test: share the delivery of the pending render in a helper --- pkg/ui/panes/diffviewer/osc1717_test.go | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/pkg/ui/panes/diffviewer/osc1717_test.go b/pkg/ui/panes/diffviewer/osc1717_test.go index 246353e..10f9144 100644 --- a/pkg/ui/panes/diffviewer/osc1717_test.go +++ b/pkg/ui/panes/diffviewer/osc1717_test.go @@ -132,6 +132,12 @@ func showing(t *testing.T, height int, lines []diffLine) Model { return m } +// rendered delivers the pending side-by-side render of a.go. +func rendered(m Model, lines []diffLine) Model { + m, _ = m.Update(diffContentMsg{cacheKey: cacheKey("a.go", true), node: m.file, lines: lines}) + return m +} + func TestFindRecord(t *testing.T) { a := func(n int) record { return record{Kind: 'a', NewLine: n, File: "a.go"} } d := func(n, o int) record { return record{Kind: 'd', NewLine: n, OldLine: o, File: "a.go"} } @@ -201,7 +207,7 @@ func TestSetSideBySide_UserMoveDuringRender(t *testing.T) { m.SetSideBySide(true) // renders async: the anchor is pending m, _ = m.Update(tea.KeyPressMsg{Code: rune(key[0]), Text: key}) - m, _ = m.Update(diffContentMsg{cacheKey: cacheKey("a.go", true), node: m.file, lines: sbs}) + m = rendered(m, sbs) metrics := m.fvp.GetItemMetrics() got, _ := firstRecord(sbs, metrics.FirstVisibleItemIdx) switch { @@ -223,7 +229,7 @@ func TestSetSideBySide_WheelWithoutMoveKeepsAnchor(t *testing.T) { m.SetSideBySide(true) m.ScrollDown(3) // the wheel at the bottom doesn't move - m, _ = m.Update(diffContentMsg{cacheKey: cacheKey("a.go", true), node: m.file, lines: sbs}) + m = rendered(m, sbs) if got, _ := firstRecord(sbs, m.fvp.GetItemMetrics().FirstVisibleItemIdx); got != want { t.Fatalf("expected line %d at the top, got line %d", want.NewLine, got.NewLine) } @@ -236,7 +242,7 @@ func TestSetSideBySide_WheelDuringRender(t *testing.T) { m.SetSideBySide(true) // renders async: the anchor is pending m.ScrollDown(3) // the wheel moves the old render - m, _ = m.Update(diffContentMsg{cacheKey: cacheKey("a.go", true), node: m.file, lines: sbs}) + m = rendered(m, sbs) if got, _ := firstRecord(sbs, m.fvp.GetItemMetrics().FirstVisibleItemIdx); got != ctxLine(9) { t.Fatalf("expected line 9 at the top, got line %d", got.NewLine) @@ -271,7 +277,7 @@ func TestSetSideBySide_EdgeKeyAtTheEdge(t *testing.T) { m.SetSideBySide(true) m, _ = m.Update(tea.KeyPressMsg{Code: rune(key[0]), Text: key}) // already there - m, _ = m.Update(diffContentMsg{cacheKey: cacheKey("a.go", true), node: m.file, lines: sbs}) + m = rendered(m, sbs) metrics := m.fvp.GetItemMetrics() if key == "g" && metrics.FirstVisibleItemIdx != 0 { t.Errorf("g: expected the top, got row %d", metrics.FirstVisibleItemIdx) @@ -290,7 +296,7 @@ func TestSetSideBySide_ResizeDuringRenderKeepsAnchor(t *testing.T) { m.SetSideBySide(true) m, _ = m.Update(tea.KeyPressMsg{Code: 'G', Text: "G"}) m.SetSize(81, 6) // a resize before the render lands - m, _ = m.Update(diffContentMsg{cacheKey: cacheKey("a.go", true), node: m.file, lines: sbs}) + m = rendered(m, sbs) if got := m.fvp.GetItemMetrics().LastVisibleItemIdx; got != len(sbs)-1 { t.Fatalf("expected the bottom, got row %d", got) } From d1f2aba7e003b29466bfb8ffd4ff9c74bb1d597b Mon Sep 17 00:00:00 2001 From: Pablo Speciale Date: Thu, 26 Nov 2026 22:20:45 +0100 Subject: [PATCH 29/32] test: keep G when the wheel doesn't move at the bottom The old wheel test kept passing without reanchor's row-unchanged check, since keepPosition no longer replaces a pending anchor. The check only matters after g/G, so test that. --- pkg/ui/panes/diffviewer/osc1717_test.go | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/pkg/ui/panes/diffviewer/osc1717_test.go b/pkg/ui/panes/diffviewer/osc1717_test.go index 10f9144..927c0b3 100644 --- a/pkg/ui/panes/diffviewer/osc1717_test.go +++ b/pkg/ui/panes/diffviewer/osc1717_test.go @@ -221,17 +221,17 @@ func TestSetSideBySide_UserMoveDuringRender(t *testing.T) { } } -func TestSetSideBySide_WheelWithoutMoveKeepsAnchor(t *testing.T) { +func TestSetSideBySide_WheelAtTheBottomKeepsG(t *testing.T) { unified, sbs := unifiedAndSbs() m := showing(t, 4, unified) - m.fvp.GoToBottom() - want, _ := firstRecord(unified, m.fvp.GetItemMetrics().FirstVisibleItemIdx) + m.ScrollDown(5) - m.SetSideBySide(true) - m.ScrollDown(3) // the wheel at the bottom doesn't move + m.SetSideBySide(true) // renders async: the anchor is pending + m, _ = m.Update(tea.KeyPressMsg{Code: 'G', Text: "G"}) + m.ScrollDown(3) // already at the bottom: doesn't move m = rendered(m, sbs) - if got, _ := firstRecord(sbs, m.fvp.GetItemMetrics().FirstVisibleItemIdx); got != want { - t.Fatalf("expected line %d at the top, got line %d", want.NewLine, got.NewLine) + if got := m.fvp.GetItemMetrics().LastVisibleItemIdx; got != len(sbs)-1 { + t.Fatalf("expected the bottom, got last row %d", got) } } From 3ca4c0836360c1771c4a6497e722bec4108ea24a Mon Sep 17 00:00:00 2001 From: Dolev Hadar Date: Mon, 30 Nov 2026 22:47:34 +0200 Subject: [PATCH 30/32] chore: slight renaming and docs --- pkg/ui/panes/diffviewer/diffviewer.go | 49 ++++++++-------- pkg/ui/panes/diffviewer/osc1717.go | 75 +++++++++++++++---------- pkg/ui/panes/diffviewer/osc1717_test.go | 46 ++++++++------- 3 files changed, 95 insertions(+), 75 deletions(-) diff --git a/pkg/ui/panes/diffviewer/diffviewer.go b/pkg/ui/panes/diffviewer/diffviewer.go index fb3f268..c52978e 100644 --- a/pkg/ui/panes/diffviewer/diffviewer.go +++ b/pkg/ui/panes/diffviewer/diffviewer.go @@ -43,7 +43,7 @@ func cacheKey(path string, sideBySide bool) string { type diffLine struct { item item.Item - records []record + records []oscRecord } func (o diffLine) GetItem() item.Item { @@ -102,11 +102,13 @@ type Model struct { anchor *scrollAnchor } -// scrollAnchor is where to scroll back to after a re-render: the top or bottom of the -// diff, or a diff line and the view's offset from its first row. +// scrollAnchor is where to scroll back to after a re-render type scrollAnchor struct { - edge anchorEdge - rec record + // whether the user explicitly navigated to the top or bottom + edge anchorEdge + + // otherwise - the position the view was in: the line's osc record and the view's offset from its first row. + oscRec oscRecord offset int } @@ -290,7 +292,7 @@ func (m Model) View() string { func (m *Model) SetSize(width, height int) tea.Cmd { // Before resizing: the viewport clamps its top row to the new size. - m.keepPosition() + m.saveAnchor() m.Width = width m.Height = height m.fvp.SetWidth(m.contentWidth()) @@ -300,32 +302,31 @@ func (m *Model) SetSize(width, height int) tea.Cmd { } func (m *Model) UpdateTheme() tea.Cmd { - m.keepPosition() + m.saveAnchor() m.ClearCache() return m.diff() } -// keepPosition remembers the diff line at the top of the view (or the selected one) and +// saveAnchor remembers the diff osc record at the top of the view (or the selected one) and // the view's offset from its first row, so the next render scrolls back to it (anchorRow). -func (m *Model) keepPosition() { - // A pending anchor still holds: the view can't have moved since without a reanchor, - // and a resize may already have clamped it. +func (m *Model) saveAnchor() { + // there's already a valid anchor if m.anchor != nil { return } - if rec, ok := m.currentRecord(); ok { - m.anchor = &scrollAnchor{rec: rec, offset: m.currentRow() - findRecord(m.shown, rec)} + if rec, ok := m.currentOSCRecord(); ok { + m.anchor = &scrollAnchor{oscRec: rec, offset: m.currentRow() - findOSCRecord(m.shown, rec)} } } -// currentRecord returns the first record at or below the current row of the lines on -// screen, so it is right while a new render is pending too. -func (m *Model) currentRecord() (record, bool) { +// currentOSCRecord returns the first record at or below the current row of the lines on +// screen, so it is correct even while a new render is pending. +func (m *Model) currentOSCRecord() (oscRecord, bool) { row := m.currentRow() if row < 0 || m.fvp.GetMatchingItemsOnly() { - return record{}, false + return oscRecord{}, false } - return firstRecord(m.shown, row) + return firstOSCRecord(m.shown, row) } // currentRow is the selected row, or the top visible one without a selection. @@ -350,7 +351,7 @@ func (m *Model) reanchor(row int, edge anchorEdge) { return } m.anchor = nil - m.keepPosition() + m.saveAnchor() } // setLines shows lines and scrolls to the pending anchor, if any. @@ -373,7 +374,7 @@ func (m *Model) setLines(lines []diffLine) { if m.fvp.GetMatchingItemsOnly() { return } - row, ok := anchorRow(lines, a.rec, a.offset) + row, ok := anchorRow(lines, a.oscRec, a.offset) if !ok { return } @@ -388,8 +389,8 @@ func (m *Model) setLines(lines []diffLine) { // anchorRow returns the row offset rows from rec's first row, or false when rec is gone. // Rows above it (offset < 0) have no record, like blank or decoration rows. Rows below it // are its wrapped rows, so it stops at the line's last row. -func anchorRow(lines []diffLine, rec record, offset int) (int, bool) { - row := findRecord(lines, rec) +func anchorRow(lines []diffLine, rec oscRecord, offset int) (int, bool) { + row := findOSCRecord(lines, rec) if row < 0 { return 0, false } @@ -397,7 +398,7 @@ func anchorRow(lines []diffLine, rec record, offset int) (int, bool) { return max(row+offset, 0), true } for range offset { - if row+1 == len(lines) || !lines[row+1].shows(rec) { + if row+1 == len(lines) || !lines[row+1].showsOSCRecord(rec) { break } row++ @@ -566,7 +567,7 @@ func (m *Model) updateHeader() { // SetSideBySide updates the diff view mode and re-renders. func (m *Model) SetSideBySide(sideBySide bool) tea.Cmd { m.sideBySide = sideBySide - m.keepPosition() + m.saveAnchor() return m.diff() } diff --git a/pkg/ui/panes/diffviewer/osc1717.go b/pkg/ui/panes/diffviewer/osc1717.go index d72172e..71b2c9f 100644 --- a/pkg/ui/panes/diffviewer/osc1717.go +++ b/pkg/ui/panes/diffviewer/osc1717.go @@ -11,14 +11,21 @@ import ( // OSC 1717 diff line metadata (https://github.com/stefanhaller/diff-line-metadata-spec). // Delta >= 0.20 emits it when OSC1717=V1 is set; older versions ignore the variable. const ( - osc1717Prefix = "\x1b]1717;" - osc1717Term = "\x1b\\" - osc1717Handshake = osc1717Prefix + "1" + osc1717Term + osc1717Prefix = "\x1b]1717;" + osc1717Term = "\x1b\\" + osc1717Handshake = osc1717Prefix + "1" + osc1717Term + osc1717Version = "1" + osc1717VersionField = 0 + osc1717TypeField = 1 + osc1717NewLineField = 2 + osc1717OldLineField = 3 + osc1717FileField = 4 + osc1717NumFields = 5 ) -// record says which diff line a row shows. +// oscRecord says which diff line a row shows. // Kind is c (context), a (added), d (deleted), f (file header) or h (hunk header). -type record struct { +type oscRecord struct { Kind byte NewLine int OldLine int @@ -36,48 +43,54 @@ func parseDeltaOutput(out string) []diffLine { rows := strings.Split(rest, "\n") lines := make([]diffLine, len(rows)) for i, row := range rows { - text, records := parseRecords(row) + text, records := parseOSCRecords(row) lines[i] = diffLine{item: item.NewItem(text), records: records} } return lines } -// parseRecords removes the OSC 1717 sequences from a row and returns them. -func parseRecords(row string) (string, []record) { +// parseOSCRecords removes the OSC 1717 sequences from a row and returns them. +func parseOSCRecords(row string) (string, []oscRecord) { if !strings.Contains(row, osc1717Prefix) { return row, nil } - var records []record + var records []oscRecord var b strings.Builder for { before, after, ok := strings.Cut(row, osc1717Prefix) if !ok { break } - body, rest, ok := strings.Cut(after, osc1717Term) + oscRecord, diffLine, ok := strings.Cut(after, osc1717Term) if !ok { break // unterminated: kept as text } b.WriteString(before) - if r, ok := parseRecord(body); ok { + if r, ok := parseOSCRecord(oscRecord); ok { records = append(records, r) } - row = rest + row = diffLine } b.WriteString(row) return b.String(), records } -// parseRecord parses ";;;;". -func parseRecord(body string) (record, bool) { - fields := strings.SplitN(body, ";", 5) - if len(fields) != 5 || fields[0] != "1" || len(fields[1]) != 1 || - !strings.Contains("cadfh", fields[1]) { - return record{}, false +// parseOSCRecord parses ";;;;". +func parseOSCRecord(body string) (oscRecord, bool) { + fields := strings.SplitN(body, ";", osc1717NumFields) + if len(fields) != osc1717NumFields || fields[osc1717VersionField] != osc1717Version || + len(fields[osc1717TypeField]) != 1 || + !strings.Contains("cadfh", fields[osc1717TypeField]) { + return oscRecord{}, false + } + newLine, _ := strconv.Atoi(fields[osc1717NewLineField]) + oldLine, _ := strconv.Atoi(fields[osc1717OldLineField]) + r := oscRecord{ + Kind: fields[osc1717TypeField][0], + NewLine: newLine, + OldLine: oldLine, + File: unquote(fields[osc1717FileField]), } - newLine, _ := strconv.Atoi(fields[2]) - oldLine, _ := strconv.Atoi(fields[3]) - r := record{Kind: fields[1][0], NewLine: newLine, OldLine: oldLine, File: unquote(fields[4])} return r, true } @@ -97,29 +110,29 @@ func unquote(file string) string { return file } -// firstRecord returns the first record at or below row. -func firstRecord(lines []diffLine, row int) (record, bool) { +// firstOSCRecord returns the first record at or below row. +func firstOSCRecord(lines []diffLine, row int) (oscRecord, bool) { for i := max(row, 0); i < len(lines); i++ { if len(lines[i].records) > 0 { return lines[i].records[0], true } } - return record{}, false + return oscRecord{}, false } -// findRecord returns the first row showing the same diff line as want, or -1. -func findRecord(lines []diffLine, want record) int { - return slices.IndexFunc(lines, func(l diffLine) bool { return l.shows(want) }) +// findOSCRecord returns the first row showing the same diff line as want, or -1. +func findOSCRecord(lines []diffLine, want oscRecord) int { + return slices.IndexFunc(lines, func(l diffLine) bool { return l.showsOSCRecord(want) }) } -// shows reports whether the row shows the same diff line as want. -func (o diffLine) shows(want record) bool { - return slices.ContainsFunc(o.records, func(r record) bool { return sameLine(r, want) }) +// showsOSCRecord reports whether the row shows the same diff line as want. +func (o diffLine) showsOSCRecord(want oscRecord) bool { + return slices.ContainsFunc(o.records, func(r oscRecord) bool { return sameLine(r, want) }) } // sameLine reports whether r is the same diff line as want: in the same file, d by old line, // c and a by new line, f and h by kind and new line. -func sameLine(r, want record) bool { +func sameLine(r, want oscRecord) bool { if r.File != want.File { return false } diff --git a/pkg/ui/panes/diffviewer/osc1717_test.go b/pkg/ui/panes/diffviewer/osc1717_test.go index 927c0b3..8e99c35 100644 --- a/pkg/ui/panes/diffviewer/osc1717_test.go +++ b/pkg/ui/panes/diffviewer/osc1717_test.go @@ -14,6 +14,7 @@ import ( func osc(body string) string { return osc1717Prefix + body + osc1717Term } +// osc1717 structure: ";;;;". func TestParseDeltaOutput(t *testing.T) { out := osc1717Handshake + osc("1;f;;;a.go") + "a.go\n" + osc("1;h;10;;a.go") + "@@\n" + @@ -26,7 +27,7 @@ func TestParseDeltaOutput(t *testing.T) { if len(lines) != 6 { t.Fatalf("expected 6 rows, got %d", len(lines)) } - want := [][]record{ + want := [][]oscRecord{ {{Kind: 'f', File: "a.go"}}, {{Kind: 'h', NewLine: 10, File: "a.go"}}, nil, @@ -53,7 +54,7 @@ func TestParseRecords_UnquotesFileName(t *testing.T) { `"\303\244.txt"`: "ä.txt", // a rename keeps git's quotes `a\q.txt`: `a\q.txt`, // not a valid escape: kept as is } { - _, records := parseRecords(osc("1;c;1;;"+raw) + "x") + _, records := parseOSCRecords(osc("1;c;1;;"+raw) + "x") if len(records) != 1 || records[0].File != want { t.Errorf("%s: expected file %q, got %+v", raw, want, records) } @@ -85,7 +86,7 @@ func TestParseDeltaOutput_RealDelta(t *testing.T) { t.Skip("delta has no OSC 1717 support") } - var got []record + var got []oscRecord for _, l := range parseDeltaOutput(string(out)) { for _, r := range l.records { if r.Kind == 'c' || r.Kind == 'a' || r.Kind == 'd' { @@ -93,7 +94,7 @@ func TestParseDeltaOutput_RealDelta(t *testing.T) { } } } - want := []record{ + want := []oscRecord{ {Kind: 'c', NewLine: 1, File: "a;b.go"}, {Kind: 'c', NewLine: 1, File: "a;b.go"}, {Kind: 'd', NewLine: 2, OldLine: 2, File: "a;b.go"}, @@ -104,12 +105,12 @@ func TestParseDeltaOutput_RealDelta(t *testing.T) { } } -func row(records ...record) diffLine { +func row(records ...oscRecord) diffLine { return diffLine{item: item.NewItem("x"), records: records} } // ctxLine is a context line n of a.go. -func ctxLine(n int) record { return record{Kind: 'c', NewLine: n, File: "a.go"} } +func ctxLine(n int) oscRecord { return oscRecord{Kind: 'c', NewLine: n, File: "a.go"} } // unifiedAndSbs returns lines 1 to 20 of a.go in unified, and side by side with a // decoration row before every line. @@ -139,12 +140,12 @@ func rendered(m Model, lines []diffLine) Model { } func TestFindRecord(t *testing.T) { - a := func(n int) record { return record{Kind: 'a', NewLine: n, File: "a.go"} } - d := func(n, o int) record { return record{Kind: 'd', NewLine: n, OldLine: o, File: "a.go"} } + a := func(n int) oscRecord { return oscRecord{Kind: 'a', NewLine: n, File: "a.go"} } + d := func(n, o int) oscRecord { return oscRecord{Kind: 'd', NewLine: n, OldLine: o, File: "a.go"} } // Side-by-side: a modification is one row with d and a. lines := []diffLine{ - row(record{Kind: 'f', File: "a.go"}), - row(record{Kind: 'h', NewLine: 1, File: "a.go"}), + row(oscRecord{Kind: 'f', File: "a.go"}), + row(oscRecord{Kind: 'h', NewLine: 1, File: "a.go"}), row(ctxLine(1), ctxLine(1)), row(d(2, 2), a(2)), row(a(3)), @@ -153,20 +154,20 @@ func TestFindRecord(t *testing.T) { } tests := []struct { name string - want record + want oscRecord row int }{ {"deleted by old line", d(99, 2), 3}, {"deleted, other old line", d(2, 99), -1}, {"added on the right of a row", a(2), 3}, {"added", a(3), 4}, - {"hunk", record{Kind: 'h', NewLine: 1, File: "a.go"}, 1}, - {"file", record{Kind: 'f', File: "a.go"}, 0}, + {"hunk", oscRecord{Kind: 'h', NewLine: 1, File: "a.go"}, 1}, + {"file", oscRecord{Kind: 'f', File: "a.go"}, 0}, {"past the end", ctxLine(9), -1}, - {"other file", record{Kind: 'c', NewLine: 1, File: "b.go"}, -1}, + {"other file", oscRecord{Kind: 'c', NewLine: 1, File: "b.go"}, -1}, } for _, tt := range tests { - if got := findRecord(lines, tt.want); got != tt.row { + if got := findOSCRecord(lines, tt.want); got != tt.row { t.Errorf("%s: expected row %d, got %d", tt.name, tt.row, got) } } @@ -209,7 +210,7 @@ func TestSetSideBySide_UserMoveDuringRender(t *testing.T) { m, _ = m.Update(tea.KeyPressMsg{Code: rune(key[0]), Text: key}) m = rendered(m, sbs) metrics := m.fvp.GetItemMetrics() - got, _ := firstRecord(sbs, metrics.FirstVisibleItemIdx) + got, _ := firstOSCRecord(sbs, metrics.FirstVisibleItemIdx) switch { case key == "g" && metrics.FirstVisibleItemIdx != 0: t.Errorf("g: expected the top, got row %d", metrics.FirstVisibleItemIdx) @@ -244,13 +245,18 @@ func TestSetSideBySide_WheelDuringRender(t *testing.T) { m.ScrollDown(3) // the wheel moves the old render m = rendered(m, sbs) - if got, _ := firstRecord(sbs, m.fvp.GetItemMetrics().FirstVisibleItemIdx); got != ctxLine(9) { + if got, _ := firstOSCRecord( + sbs, + m.fvp.GetItemMetrics().FirstVisibleItemIdx, + ); got != ctxLine( + 9, + ) { t.Fatalf("expected line 9 at the top, got line %d", got.NewLine) } } func TestSwitchToUncachedNode_HasNoRecord(t *testing.T) { - a := []diffLine{row(record{Kind: 'c', NewLine: 40, File: "a.go"})} + a := []diffLine{row(oscRecord{Kind: 'c', NewLine: 40, File: "a.go"})} b := &gitdiff.File{OldName: "b.go", NewName: "b.go"} switches := map[string]func(Model) Model{ "file": func(m Model) Model { m, _ = m.SetFilePatch(b); return m }, @@ -261,7 +267,7 @@ func TestSwitchToUncachedNode_HasNoRecord(t *testing.T) { m.SetSize(80, 6) m.setLines(a) m = switchTo(m) - if rec, ok := m.currentRecord(); ok { + if rec, ok := m.currentOSCRecord(); ok { t.Errorf("%s: expected no record before the render lands, got %+v", name, rec) } } @@ -307,7 +313,7 @@ func TestAnchorRow(t *testing.T) { lines := []diffLine{row(), row(ctxLine(1)), row(ctxLine(1)), row(ctxLine(2))} tests := []struct { name string - rec record + rec oscRecord offset int row int ok bool From 57e99f1687b8fb29ecf98154684bf5cea86daf6e Mon Sep 17 00:00:00 2001 From: Dolev Hadar Date: Fri, 4 Dec 2026 13:08:23 +0200 Subject: [PATCH 31/32] refactor: put things in consts --- pkg/ui/panes/diffviewer/osc1717.go | 35 ++++++++++++++--------- pkg/ui/panes/diffviewer/osc1717_test.go | 38 ++++++++++++------------- 2 files changed, 40 insertions(+), 33 deletions(-) diff --git a/pkg/ui/panes/diffviewer/osc1717.go b/pkg/ui/panes/diffviewer/osc1717.go index 71b2c9f..7c77212 100644 --- a/pkg/ui/panes/diffviewer/osc1717.go +++ b/pkg/ui/panes/diffviewer/osc1717.go @@ -10,17 +10,23 @@ import ( // OSC 1717 diff line metadata (https://github.com/stefanhaller/diff-line-metadata-spec). // Delta >= 0.20 emits it when OSC1717=V1 is set; older versions ignore the variable. + const ( - osc1717Prefix = "\x1b]1717;" - osc1717Term = "\x1b\\" - osc1717Handshake = osc1717Prefix + "1" + osc1717Term - osc1717Version = "1" - osc1717VersionField = 0 - osc1717TypeField = 1 - osc1717NewLineField = 2 - osc1717OldLineField = 3 - osc1717FileField = 4 - osc1717NumFields = 5 + osc1717Prefix = "\x1b]1717;" + osc1717Term = "\x1b\\" + osc1717Handshake = osc1717Prefix + "1" + osc1717Term + osc1717Version = "1" + osc1717VersionField = 0 + osc1717TypeField = 1 + osc1717NewLineField = 2 + osc1717OldLineField = 3 + osc1717FileField = 4 + osc1717NumFields = 5 + osc1717KindDeleted = 'd' + osc1717KindContext = 'c' + osc1717KindAdded = 'a' + osc1717KindFileHeader = 'f' + osc1717KindHunkHeader = 'h' ) // oscRecord says which diff line a row shows. @@ -137,10 +143,11 @@ func sameLine(r, want oscRecord) bool { return false } switch want.Kind { - case 'd': - return r.Kind == 'd' && r.OldLine == want.OldLine - case 'c', 'a': - return (r.Kind == 'c' || r.Kind == 'a') && r.NewLine == want.NewLine + case osc1717KindDeleted: + return r.Kind == osc1717KindDeleted && r.OldLine == want.OldLine + case osc1717KindContext, osc1717KindAdded: + return (r.Kind == osc1717KindContext || r.Kind == osc1717KindAdded) && + r.NewLine == want.NewLine default: return r.Kind == want.Kind && r.NewLine == want.NewLine } diff --git a/pkg/ui/panes/diffviewer/osc1717_test.go b/pkg/ui/panes/diffviewer/osc1717_test.go index 8e99c35..4914bde 100644 --- a/pkg/ui/panes/diffviewer/osc1717_test.go +++ b/pkg/ui/panes/diffviewer/osc1717_test.go @@ -28,14 +28,14 @@ func TestParseDeltaOutput(t *testing.T) { t.Fatalf("expected 6 rows, got %d", len(lines)) } want := [][]oscRecord{ - {{Kind: 'f', File: "a.go"}}, - {{Kind: 'h', NewLine: 10, File: "a.go"}}, + {{Kind: osc1717KindFileHeader, File: "a.go"}}, + {{Kind: osc1717KindHunkHeader, NewLine: 10, File: "a.go"}}, nil, { - {Kind: 'd', NewLine: 10, OldLine: 9, File: "a.go"}, - {Kind: 'a', NewLine: 10, File: "a.go"}, + {Kind: osc1717KindDeleted, NewLine: 10, OldLine: 9, File: "a.go"}, + {Kind: osc1717KindAdded, NewLine: 10, File: "a.go"}, }, - {{Kind: 'c', NewLine: 11, File: "dir;b.go"}}, + {{Kind: osc1717KindContext, NewLine: 11, File: "dir;b.go"}}, nil, // unknown type and version } for i, l := range lines { @@ -89,16 +89,16 @@ func TestParseDeltaOutput_RealDelta(t *testing.T) { var got []oscRecord for _, l := range parseDeltaOutput(string(out)) { for _, r := range l.records { - if r.Kind == 'c' || r.Kind == 'a' || r.Kind == 'd' { + if r.Kind == osc1717KindContext || r.Kind == osc1717KindAdded || r.Kind == osc1717KindDeleted { got = append(got, r) } } } want := []oscRecord{ - {Kind: 'c', NewLine: 1, File: "a;b.go"}, - {Kind: 'c', NewLine: 1, File: "a;b.go"}, - {Kind: 'd', NewLine: 2, OldLine: 2, File: "a;b.go"}, - {Kind: 'a', NewLine: 2, File: "a;b.go"}, + {Kind: osc1717KindContext, NewLine: 1, File: "a;b.go"}, + {Kind: osc1717KindContext, NewLine: 1, File: "a;b.go"}, + {Kind: osc1717KindDeleted, NewLine: 2, OldLine: 2, File: "a;b.go"}, + {Kind: osc1717KindAdded, NewLine: 2, File: "a;b.go"}, } if !reflect.DeepEqual(got, want) { t.Fatalf("expected %+v, got %+v", want, got) @@ -110,7 +110,7 @@ func row(records ...oscRecord) diffLine { } // ctxLine is a context line n of a.go. -func ctxLine(n int) oscRecord { return oscRecord{Kind: 'c', NewLine: n, File: "a.go"} } +func ctxLine(n int) oscRecord { return oscRecord{Kind: osc1717KindContext, NewLine: n, File: "a.go"} } // unifiedAndSbs returns lines 1 to 20 of a.go in unified, and side by side with a // decoration row before every line. @@ -140,12 +140,12 @@ func rendered(m Model, lines []diffLine) Model { } func TestFindRecord(t *testing.T) { - a := func(n int) oscRecord { return oscRecord{Kind: 'a', NewLine: n, File: "a.go"} } - d := func(n, o int) oscRecord { return oscRecord{Kind: 'd', NewLine: n, OldLine: o, File: "a.go"} } + a := func(n int) oscRecord { return oscRecord{Kind: osc1717KindAdded, NewLine: n, File: "a.go"} } + d := func(n, o int) oscRecord { return oscRecord{Kind: osc1717KindDeleted, NewLine: n, OldLine: o, File: "a.go"} } // Side-by-side: a modification is one row with d and a. lines := []diffLine{ - row(oscRecord{Kind: 'f', File: "a.go"}), - row(oscRecord{Kind: 'h', NewLine: 1, File: "a.go"}), + row(oscRecord{Kind: osc1717KindFileHeader, File: "a.go"}), + row(oscRecord{Kind: osc1717KindHunkHeader, NewLine: 1, File: "a.go"}), row(ctxLine(1), ctxLine(1)), row(d(2, 2), a(2)), row(a(3)), @@ -161,10 +161,10 @@ func TestFindRecord(t *testing.T) { {"deleted, other old line", d(2, 99), -1}, {"added on the right of a row", a(2), 3}, {"added", a(3), 4}, - {"hunk", oscRecord{Kind: 'h', NewLine: 1, File: "a.go"}, 1}, - {"file", oscRecord{Kind: 'f', File: "a.go"}, 0}, + {"hunk", oscRecord{Kind: osc1717KindHunkHeader, NewLine: 1, File: "a.go"}, 1}, + {"file", oscRecord{Kind: osc1717KindFileHeader, File: "a.go"}, 0}, {"past the end", ctxLine(9), -1}, - {"other file", oscRecord{Kind: 'c', NewLine: 1, File: "b.go"}, -1}, + {"other file", oscRecord{Kind: osc1717KindContext, NewLine: 1, File: "b.go"}, -1}, } for _, tt := range tests { if got := findOSCRecord(lines, tt.want); got != tt.row { @@ -256,7 +256,7 @@ func TestSetSideBySide_WheelDuringRender(t *testing.T) { } func TestSwitchToUncachedNode_HasNoRecord(t *testing.T) { - a := []diffLine{row(oscRecord{Kind: 'c', NewLine: 40, File: "a.go"})} + a := []diffLine{row(oscRecord{Kind: osc1717KindContext, NewLine: 40, File: "a.go"})} b := &gitdiff.File{OldName: "b.go", NewName: "b.go"} switches := map[string]func(Model) Model{ "file": func(m Model) Model { m, _ = m.SetFilePatch(b); return m }, From ecc637caae14d2eaa5579992f0611ee859cfb66a Mon Sep 17 00:00:00 2001 From: Dolev Hadar Date: Fri, 4 Dec 2026 13:11:11 +0200 Subject: [PATCH 32/32] chore: lint --- pkg/ui/panes/diffviewer/osc1717_test.go | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/pkg/ui/panes/diffviewer/osc1717_test.go b/pkg/ui/panes/diffviewer/osc1717_test.go index 4914bde..ab92f7d 100644 --- a/pkg/ui/panes/diffviewer/osc1717_test.go +++ b/pkg/ui/panes/diffviewer/osc1717_test.go @@ -89,7 +89,8 @@ func TestParseDeltaOutput_RealDelta(t *testing.T) { var got []oscRecord for _, l := range parseDeltaOutput(string(out)) { for _, r := range l.records { - if r.Kind == osc1717KindContext || r.Kind == osc1717KindAdded || r.Kind == osc1717KindDeleted { + if r.Kind == osc1717KindContext || r.Kind == osc1717KindAdded || + r.Kind == osc1717KindDeleted { got = append(got, r) } } @@ -110,7 +111,11 @@ func row(records ...oscRecord) diffLine { } // ctxLine is a context line n of a.go. -func ctxLine(n int) oscRecord { return oscRecord{Kind: osc1717KindContext, NewLine: n, File: "a.go"} } +func ctxLine( + n int, +) oscRecord { + return oscRecord{Kind: osc1717KindContext, NewLine: n, File: "a.go"} +} // unifiedAndSbs returns lines 1 to 20 of a.go in unified, and side by side with a // decoration row before every line. @@ -141,7 +146,9 @@ func rendered(m Model, lines []diffLine) Model { func TestFindRecord(t *testing.T) { a := func(n int) oscRecord { return oscRecord{Kind: osc1717KindAdded, NewLine: n, File: "a.go"} } - d := func(n, o int) oscRecord { return oscRecord{Kind: osc1717KindDeleted, NewLine: n, OldLine: o, File: "a.go"} } + d := func(n, o int) oscRecord { + return oscRecord{Kind: osc1717KindDeleted, NewLine: n, OldLine: o, File: "a.go"} + } // Side-by-side: a modification is one row with d and a. lines := []diffLine{ row(oscRecord{Kind: osc1717KindFileHeader, File: "a.go"}),