From d42b5b29216d5fff0cdf780e413e1d6031d9826b Mon Sep 17 00:00:00 2001 From: Kenichiro Goto Date: Sun, 8 Nov 2026 20:22:35 +0900 Subject: [PATCH 01/11] tui: drop list focus when the file list hides z kept the focus on a hidden list, so j and k moved through files that did not show. Hiding now gives the keys back to the code, and tab on a hidden list shows it again. --- tui/nav.go | 5 +++++ tui/tui_test.go | 15 +++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/tui/nav.go b/tui/nav.go index d8dd8c3..7ee3dbc 100644 --- a/tui/nav.go +++ b/tui/nav.go @@ -127,6 +127,10 @@ func (m *model) moveKey(msg tea.KeyPressMsg) (tea.Cmd, bool) { switch { case key.Matches(msg, k.Focus): m.focusList = !m.focusList + if m.focusList && m.listHidden { // focus on a hidden list shows it + m.listHidden = false + m.rerender() + } case key.Matches(msg, k.Down) && inList: m.pickFile(m.listSel() + 1) case key.Matches(msg, k.Down): @@ -233,6 +237,7 @@ func (m *model) viewKey(msg tea.KeyPressMsg) (tea.Cmd, bool) { m.listLeft = !m.listLeft case key.Matches(msg, k.NavHide): m.listHidden = !m.listHidden + m.focusList = m.focusList && !m.listHidden // j and k go back to the code m.rerender() case key.Matches(msg, k.NavGrow): m.listW = min(m.listW+listWidthStep, m.w/2) diff --git a/tui/tui_test.go b/tui/tui_test.go index 520f3dc..102d48c 100644 --- a/tui/tui_test.go +++ b/tui/tui_test.go @@ -87,6 +87,7 @@ func press(t *testing.T, m model, keys ...string) model { "esc": tea.KeyEscape, "home": tea.KeyHome, "end": tea.KeyEnd, + "tab": tea.KeyTab, } for _, k := range keys { code, ok := named[k] @@ -962,3 +963,17 @@ func TestParseGuide(t *testing.T) { t.Error("parseGuide of no JSON: no error") } } + +// TestHideList checks that z hides the file list and gives j and k back to +// the code, and that tab on a hidden list shows it again. +func TestHideList(t *testing.T) { + m, _ := newTestModel(t) + m = press(t, m, "tab", "z") + if m.listWidth() != 0 || m.focusList { + t.Fatalf("z: list width %d, focus %v", m.listWidth(), m.focusList) + } + m = press(t, m, "tab") + if m.listWidth() == 0 || !m.focusList { + t.Fatalf("tab: list width %d, focus %v", m.listWidth(), m.focusList) + } +} From 0e5295c3b6dbd598685924dfe566c6c3ee1b8c49 Mon Sep 17 00:00:00 2001 From: Kenichiro Goto Date: Sun, 8 Nov 2026 20:30:26 +0900 Subject: [PATCH 02/11] tui: show the diff side by side only in a wide main pane The split layout needed the main pane to take 60% of the screen. The file list and the guide column never take more than a third, so every width passed and a narrow pane cut both sides. The main pane now needs 80 columns, in the Diff and in the Guide tab. --- tui/render.go | 16 ++++++++-------- tui/tui_test.go | 12 ++++++++++-- 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/tui/render.go b/tui/render.go index 3d56469..b9532c0 100644 --- a/tui/render.go +++ b/tui/render.go @@ -89,16 +89,16 @@ func (m *model) rerender() { } } -// minSplitShare is the smallest share of the screen, in percent, that the -// main pane takes before a diff shows side by side. A smaller share shows the -// diff top to bottom, even if the layout is split, because each side would cut -// most lines. -const minSplitShare = 60 +// minSplitWidth is the narrowest main pane, in columns, that shows a diff +// side by side. A narrower pane shows the diff top to bottom, even if the +// layout is split, because each side would cut most lines. The width counts +// in each tab, so the Guide tab, whose column is wider than the file list, +// switches too. +const minSplitWidth = 80 -// splitShown tells if the diff shows side by side now. The main pane must -// take most of the screen, or each side would cut most lines. +// splitShown tells if the diff shows side by side now. func (m *model) splitShown() bool { - return m.split && m.w > 0 && m.mainSpace()*100 >= m.w*minSplitShare + return m.split && m.mainSpace() >= minSplitWidth } // diffOptions returns the options to render a diff with sideways scroll diff --git a/tui/tui_test.go b/tui/tui_test.go index 102d48c..b22fcdb 100644 --- a/tui/tui_test.go +++ b/tui/tui_test.go @@ -223,8 +223,8 @@ func TestComment(t *testing.T) { } } -// TestSplitThreshold checks that the diff shows side by side when the main -// pane takes about 60% of the screen. +// TestSplitThreshold checks that the diff shows side by side only when the +// main pane is wide enough, in the Diff and in the Guide tab. func TestSplitThreshold(t *testing.T) { m, _ := newTestModel(t) if !m.splitShown() { @@ -234,6 +234,14 @@ func TestSplitThreshold(t *testing.T) { if m.splitShown() { t.Error("a 40-column screen shows the diff side by side") } + // The guide column is wider than the file list. + m.tab, m.guide.sections = tabGuide, []guideSection{{Title: "x", Files: []string{"a.go"}}} + for w, want := range map[int]bool{120: false, 200: true} { + m = step(t, m, tea.WindowSizeMsg{Width: w, Height: 40}) + if m.splitShown() != want { + t.Errorf("guide at %d columns: side by side %v, want %v", w, !want, want) + } + } } func TestTabs(t *testing.T) { From c09e9f5aee84ad8a4e8faa30140740b855faf956 Mon Sep 17 00:00:00 2001 From: Kenichiro Goto Date: Sun, 8 Nov 2026 20:31:56 +0900 Subject: [PATCH 03/11] tui: show more unchanged lines around a change MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit + shows ten more lines of context around each change of the file, and - ten fewer. A click on a "↕ N unchanged lines" header does the same as +. The context goes back to three lines on the next file. --- README.md | 1 + diff/diff.go | 4 ++++ internal/diffview/diffview.go | 7 ++++--- tui/config.go | 9 ++++++--- tui/keys.go | 8 +++++++- tui/model.go | 5 +++-- tui/mouse.go | 13 +++++++++++++ tui/nav.go | 20 ++++++++++++++++++-- tui/render.go | 25 +++++++++++++++---------- tui/tui_test.go | 31 +++++++++++++++++++++++++++++++ 10 files changed, 102 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 3fb1940..f73285c 100644 --- a/README.md +++ b/README.md @@ -65,6 +65,7 @@ are gone, rexdiff marks the comment as stale. | --- | --- | | `u` `b` `t` | uncommitted, branch, or last-turn changes | | `]` `[` | next or previous change | +| `+` `-` | more or fewer unchanged lines around each change (or click `↕`) | | `f` `F` | next or previous file | | `c` | comment | | `s` | send the comments to the agent | diff --git a/diff/diff.go b/diff/diff.go index c499fda..d6210fa 100644 --- a/diff/diff.go +++ b/diff/diff.go @@ -67,6 +67,9 @@ type Options struct { // Signs marks a changed line with + or -. Without Signs, a bar in the // colour of the line marks it. Signs bool + // Context is the number of unchanged lines around each change. Zero + // means 3. [RenderFile] ignores it. + Context int // Theme sets the colours. Theme Theme } @@ -98,6 +101,7 @@ func Render(path, old, new string, o Options) *Diff { Wrap: o.Wrap, Signs: o.Signs, TabWidth: tabWidth, + Context: o.Context, Style: o.Theme.style(), }) d := &Diff{split: o.Split} diff --git a/internal/diffview/diffview.go b/internal/diffview/diffview.go index 123b529..bff2c81 100644 --- a/internal/diffview/diffview.go +++ b/internal/diffview/diffview.go @@ -36,6 +36,7 @@ type Options struct { Wrap bool // continue a long line on the next lines; Offset does not apply Signs bool // mark a changed line with + or -, not with a bar TabWidth int // the number of spaces that replace a tab; 0 means 8 + Context int // the unchanged lines around a change; 0 means 3 Style Style } @@ -101,7 +102,7 @@ type renderer struct { func Render(path, before, after string, o Options) ([]string, []Row, Geometry) { before = strings.ReplaceAll(before, "\r\n", "\n") after = strings.ReplaceAll(after, "\r\n", "\n") - hunks := diffHunks(before, after, cmp.Or(o.TabWidth, 8)) + hunks := diffHunks(before, after, cmp.Or(o.TabWidth, 8), cmp.Or(o.Context, udiff.DefaultContextLines)) r := &renderer{o: o, hl: newHighlighter(path, cmp.Or(before, after))} r.measure(hunks) for _, h := range hunks { @@ -121,8 +122,8 @@ func Render(path, before, after string, o Options) ([]string, []Row, Geometry) { // diffHunks computes the hunks of the diff, with the tabs of the lines // replaced after the diff, so that a change from a tab to spaces shows. -func diffHunks(before, after string, tabWidth int) []hunk { - u, err := udiff.ToUnifiedDiff("", "", before, udiff.Lines(before, after), udiff.DefaultContextLines) +func diffHunks(before, after string, tabWidth, context int) []hunk { + u, err := udiff.ToUnifiedDiff("", "", before, udiff.Lines(before, after), context) if err != nil { return nil } diff --git a/tui/config.go b/tui/config.go index 1b90c99..b3afddb 100644 --- a/tui/config.go +++ b/tui/config.go @@ -104,9 +104,12 @@ type keybindings struct { Expand []string `json:"expand"` NextHunk []string `json:"next-hunk"` PrevHunk []string `json:"prev-hunk"` - NextFile []string `json:"next-file"` - PrevFile []string `json:"prev-file"` - Focus []string `json:"focus"` + // MoreContext and LessContext are not actions of herdr-reviewr. + MoreContext []string `json:"more-context"` + LessContext []string `json:"less-context"` + NextFile []string `json:"next-file"` + PrevFile []string `json:"prev-file"` + Focus []string `json:"focus"` // Scopes and tabs. ScopeUncommitted []string `json:"scope-uncommitted"` diff --git a/tui/keys.go b/tui/keys.go index 7d9e807..7e386e7 100644 --- a/tui/keys.go +++ b/tui/keys.go @@ -13,6 +13,7 @@ type keyMap struct { // Move. Down, Up, PageDown, PageUp, HalfDown, HalfUp, Top, Bottom key.Binding NextHunk, PrevHunk, NextFile, PrevFile, Focus, Left, Right key.Binding + MoreContext, LessContext key.Binding // Scopes and tabs. ScopeUncommitted, ScopeBranch, ScopeTurn, ScopeCommits key.Binding @@ -68,6 +69,9 @@ func defaultKeys() keyMap { Left: bind([]string{"left"}, "←/→", "scroll sideways"), Right: bind([]string{"right"}, "→", "scroll right"), + MoreContext: bind([]string{"+", "="}, "+/-", "more/less context"), + LessContext: bind([]string{"-"}, "-", "less context"), + ScopeUncommitted: bind([]string{"u"}, "u", "uncommitted"), ScopeBranch: bind([]string{"b"}, "b", "branch"), ScopeTurn: bind([]string{"t"}, "t", "last turn"), @@ -169,6 +173,8 @@ func (k *keyMap) bindings(c keybindings) []binding { {"expand", c.Expand, &k.Right}, {"next-hunk", c.NextHunk, &k.NextHunk}, {"prev-hunk", c.PrevHunk, &k.PrevHunk}, + {"more-context", c.MoreContext, &k.MoreContext}, + {"less-context", c.LessContext, &k.LessContext}, {"next-file", c.NextFile, &k.NextFile}, {"prev-file", c.PrevFile, &k.PrevFile}, {"focus", c.Focus, &k.Focus}, @@ -275,7 +281,7 @@ func (h helpKeys) ShortHelp() []key.Binding { func (h helpKeys) FullHelp() [][]key.Binding { k := h.k move := []key.Binding{ - k.Down, k.HalfDown, k.NextHunk, k.NextFile, k.Focus, k.Left, k.GotoLine, + k.Down, k.HalfDown, k.NextHunk, k.MoreContext, k.NextFile, k.Focus, k.Left, k.GotoLine, } scopes := []key.Binding{ k.TabOverview, k.ScopeUncommitted, k.ScopeBranch, k.ScopeTurn, k.ScopeCommits, diff --git a/tui/model.go b/tui/model.go index 7edb28b..2e9be0d 100644 --- a/tui/model.go +++ b/tui/model.go @@ -82,6 +82,7 @@ type pane struct { anchor int // the start of the visual selection, or -1 text *textSelection // the text selected with the mouse, or nil xoff int // the sideways scroll, in columns + more int // the unchanged lines around a change, beyond the default note string // shown instead of the lines, if there are no lines // free is true after the wheel moves the view. Then the cursor can // be off the screen until the next key or click. @@ -120,8 +121,8 @@ func (p *pane) end(i int) int { } // toStart moves the cursor and the view to the first row. It clears the -// selection and the sideways scroll. -func (p *pane) toStart() { p.cur, p.top, p.anchor, p.text, p.xoff = 0, 0, -1, nil, 0 } +// selection, the sideways scroll, and the added context. +func (p *pane) toStart() { p.cur, p.top, p.anchor, p.text, p.xoff, p.more = 0, 0, -1, nil, 0, 0 } // setDiff shows the lines of d. func (p *pane) setDiff(d *diff.Diff) { diff --git a/tui/mouse.go b/tui/mouse.go index 0e9d7ec..a4b0dd1 100644 --- a/tui/mouse.go +++ b/tui/mouse.go @@ -7,6 +7,8 @@ package tui import ( tea "charm.land/bubbletea/v2" "charm.land/lipgloss/v2" + + "github.com/frinfo702/rexdiff/diff" ) // onClick handles a press of a mouse button. @@ -52,6 +54,11 @@ func (m *model) onClick(mouse tea.Mouse) tea.Cmd { } p := m.cur() m.focusList = false + if p.hunkHeader(rowAt[y]) { // "↕ 12 unchanged lines": show them + p.cur = rowAt[y] + m.addContext(contextStep) + return nil + } p.cur, p.anchor = p.head(rowAt[y]), -1 x := mouse.X - m.mainX() - gutter side, onNumber := p.side(x) @@ -69,6 +76,12 @@ func (m *model) onClick(mouse tea.Mouse) tea.Cmd { return nil } +// hunkHeader tells if row i is the line above a hunk of a diff. Row 0 is +// the file header. +func (p *pane) hunkHeader(i int) bool { + return p.diff != nil && i > 0 && i < len(p.rows) && p.rows[i].Kind == diff.KindHunk +} + // listIndexAt returns the file on line y of the file list, h lines tall, // or -1. func (m *model) listIndexAt(y, h int) int { diff --git a/tui/nav.go b/tui/nav.go index 7ee3dbc..bea7ed5 100644 --- a/tui/nav.go +++ b/tui/nav.go @@ -16,8 +16,9 @@ import ( // Steps of the keys that move or resize, in columns. const ( - scrollStep = 8 // the sideways scroll - listWidthStep = 4 // the width of the file list + scrollStep = 8 // the sideways scroll + listWidthStep = 4 // the width of the file list + contextStep = 10 // the unchanged lines that + adds around a change ) // updateNormal handles a key when no box is open. @@ -151,6 +152,10 @@ func (m *model) moveKey(msg tea.KeyPressMsg) (tea.Cmd, bool) { p.cur = 0 case key.Matches(msg, k.Bottom): p.cur = last + case key.Matches(msg, k.MoreContext): + m.addContext(contextStep) + case key.Matches(msg, k.LessContext): + m.addContext(-contextStep) case key.Matches(msg, k.NextHunk): m.stepChange(1) case key.Matches(msg, k.PrevHunk): @@ -257,6 +262,17 @@ func (m *model) viewKey(msg tea.KeyPressMsg) (tea.Cmd, bool) { return nil, true } +// addContext shows n more unchanged lines around each change of the diff, +// or fewer if n is negative. The cursor stays on its line. +func (m *model) addContext(n int) { + p := m.cur() + if m.tab != tabChanges && m.tab != tabGuide { + return + } + p.more = max(p.more+n, 0) + m.rerender() +} + // openPR opens the pull request in the browser. func (m *model) openPR() { if m.pr.pr == nil || m.pr.pr.URL == "" { diff --git a/tui/render.go b/tui/render.go index b9532c0..79b7e7c 100644 --- a/tui/render.go +++ b/tui/render.go @@ -101,15 +101,20 @@ func (m *model) splitShown() bool { return m.split && m.mainSpace() >= minSplitWidth } -// diffOptions returns the options to render a diff with sideways scroll -// xoff. -func (m *model) diffOptions(xoff int) diff.Options { +// contextLines is the number of unchanged lines around a change that a +// diff shows before the user asks for more. +const contextLines = 3 + +// diffOptions returns the options to render a diff in p, with its sideways +// scroll and its context. +func (m *model) diffOptions(p *pane) diff.Options { return diff.Options{ - Width: m.codeWidth(), - Offset: xoff, - Wrap: m.wrap, - Split: m.splitShown(), - Signs: m.cfg.DiffSigns, + Width: m.codeWidth(), + Offset: p.xoff, + Context: contextLines + p.more, + Wrap: m.wrap, + Split: m.splitShown(), + Signs: m.cfg.DiffSigns, Theme: diff.Theme{ Background: m.bg, Foreground: m.fg, @@ -152,7 +157,7 @@ func (m *model) renderChanged(p *pane, f *changed) { case m.rendered && isMarkdown(f.Path) && f.Status != vcs.StatusDeleted: m.setMarkdown(p, f.New) default: - p.setDiff(diff.Render(f.Path, f.Old, f.New, m.diffOptions(p.xoff))) + p.setDiff(diff.Render(f.Path, f.Old, f.New, m.diffOptions(p))) } p.addHeader(m.fileHeader(f)) } @@ -240,7 +245,7 @@ func (m *model) refreshViewer() { case m.rendered && isMarkdown(path): m.setMarkdown(p, content) default: - p.setDiff(diff.RenderFile(path, content, m.diffOptions(p.xoff))) + p.setDiff(diff.RenderFile(path, content, m.diffOptions(p))) } } diff --git a/tui/tui_test.go b/tui/tui_test.go index b22fcdb..eb21b19 100644 --- a/tui/tui_test.go +++ b/tui/tui_test.go @@ -3,6 +3,7 @@ package tui import ( "encoding/json" "errors" + "fmt" "image/color" "os" "os/exec" @@ -985,3 +986,33 @@ func TestHideList(t *testing.T) { t.Fatalf("tab: list width %d, focus %v", m.listWidth(), m.focusList) } } + +// TestMoreContext checks that + shows more unchanged lines around a +// change, that - shows fewer, and that a click on a hunk header shows more. +func TestMoreContext(t *testing.T) { + m, dir := newTestModel(t) + var src strings.Builder + for i := range 40 { + fmt.Fprintf(&src, "// line %d\n", i+1) + } + write(t, dir, "a.go", src.String()) + git(t, dir, "commit", "-qam", "long") + write(t, dir, "a.go", strings.Replace(src.String(), "line 30\n", "changed\n", 1)) + m.reload() + shown := func(line int) bool { return m.changes.rowOf(diff.SideNew, line) >= 0 } + if shown(20) { + t.Fatal("line 20 shows before + is pressed") + } + if m = press(t, m, "+"); !shown(20) { + t.Error("+ did not show line 20") + } + if m = press(t, m, "-"); shown(20) { + t.Error("- did not hide line 20") + } + h := slices.IndexFunc(m.changes.rows[1:], func(r diff.Row) bool { return r.Kind == diff.KindHunk }) + 1 + _, rowAt := m.mainLines(m.bodyHeight()) + m = click(t, m, m.mainX()+gutter+4, bodyY+slices.Index(rowAt, h)) + if !shown(20) { + t.Error("a click on the hunk header did not show line 20") + } +} From 577c54937156a6e524e1454e525375c0ebb04639 Mon Sep 17 00:00:00 2001 From: Kenichiro Goto Date: Sun, 8 Nov 2026 20:32:51 +0900 Subject: [PATCH 04/11] tui: tint the line at the cursor The line at the cursor gets a faint tint of the terminal background, to the width of the code. Cells with a background of their own, such as an added line or a text selection, keep it. The setting cursor_line = false turns the tint off. --- README.md | 1 + tui/config.go | 3 +++ tui/selection.go | 58 +++++++++++++++++++++++++++++++++++++++++++ tui/selection_test.go | 15 +++++++++++ tui/tui_test.go | 16 ++++++++++++ tui/view.go | 26 +++++++++++++++++++ 6 files changed, 119 insertions(+) diff --git a/README.md b/README.md index f73285c..8054a2e 100644 --- a/README.md +++ b/README.md @@ -111,6 +111,7 @@ Other settings: - `guide_agent`: the command that writes the guide. It reads the prompt on its standard input, for example `"claude -p --model sonnet"` - `diff_signs`: `true` marks changed lines with `+` and `-`, in place of a coloured bar +- `cursor_line`: `false` turns off the tint of the line at the cursor - `review_prefix` - `url_opener` - `focus_agent_after_send` diff --git a/tui/config.go b/tui/config.go index b3afddb..f45499e 100644 --- a/tui/config.go +++ b/tui/config.go @@ -79,6 +79,8 @@ type config struct { GuideAgent string `json:"guide_agent"` // DiffSigns marks a changed line with + or -, in place of a bar. DiffSigns bool `json:"diff_signs"` + // CursorLine tints the background of the line at the cursor. + CursorLine bool `json:"cursor_line"` // FocusAgent tells if the focus moves to the agent after a send. Nil // means true. FocusAgent *bool `json:"focus_agent_after_send"` @@ -165,6 +167,7 @@ func defaultConfig() config { MarkdownView: markdownViewSource, FileList: positionRight, FileListWidth: 32, + CursorLine: true, } } diff --git a/tui/selection.go b/tui/selection.go index 1d0774b..2e507c1 100644 --- a/tui/selection.go +++ b/tui/selection.go @@ -6,6 +6,7 @@ package tui // again and esc can clear it. import ( + "strconv" "strings" "charm.land/bubbletea/v2" @@ -150,6 +151,63 @@ func carrySGR(s, sgr string) string { return b.String() } +// underSGR puts sgr under the cells of s that have no background of their +// own, so that sgr shows only where s shows the terminal background. +func underSGR(s, sgr string) string { + var b strings.Builder + b.WriteString(sgr) + own := false // the text sets its own background now + var state byte + for len(s) > 0 { + seq, width, n, next := ansi.DecodeSequence(s, state, nil) + if n <= 0 { + b.WriteString(s) + break + } + b.WriteString(seq) + if width == 0 && strings.HasPrefix(seq, "\x1b[") && strings.HasSuffix(seq, "m") { + own = setsBackground(seq[2:len(seq)-1], own) + if !own { + b.WriteString(sgr) + } + } + s, state = s[n:], next + } + return b.String() +} + +// setsBackground tells if the text has a background of its own after the +// SGR parameters params. own tells if it had one before. +func setsBackground(params string, own bool) bool { + if params == "" { + return false // a reset + } + ps := strings.Split(params, ";") + for i := 0; i < len(ps); i++ { + p := ps[i] + if base, _, ok := strings.Cut(p, ":"); ok { // 48:2::r:g:b + own = own || base == "48" + continue + } + switch n, _ := strconv.Atoi(p); { + case n == 0 || n == 49: + own = false + case n >= 40 && n <= 47 || n >= 100 && n <= 107: + own = true + case n == 38 || n == 48 || n == 58: // 5;i or 2;r;g;b follow + if n == 48 { + own = true + } + if i+1 < len(ps) && ps[i+1] == "5" { + i += 2 + } else if i+1 < len(ps) && ps[i+1] == "2" { + i += 4 + } + } + } + return own +} + // textSelectSGR returns the sequence that marks a selection. It tints the // background, or reverses the colours if the terminal does not tell its // background. diff --git a/tui/selection_test.go b/tui/selection_test.go index 3303fb0..c404974 100644 --- a/tui/selection_test.go +++ b/tui/selection_test.go @@ -170,3 +170,18 @@ func TestMarkSelection(t *testing.T) { t.Errorf("marked line %q, want %q", got, want) } } + +// TestUnderSGR checks that the tint of the cursor line shows only on the +// cells that have no background of their own. +func TestUnderSGR(t *testing.T) { + const tint = "\x1b[48;5;1m" + green := "\x1b[38;2;48;0;0;48;2;0;9;0m" // a foreground of 48 is not a background + got := underSGR("a"+green+"b\x1b[mc\x1b[38;2;48;1;1md", tint) + want := tint + "a" + green + "b\x1b[m" + tint + "c\x1b[38;2;48;1;1m" + tint + "d" + if got != want { + t.Errorf("underSGR:\n got %q\nwant %q", got, want) + } + if setsBackground("38;2;48;0;0", false) { + t.Error("a foreground with a 48 in it counts as a background") + } +} diff --git a/tui/tui_test.go b/tui/tui_test.go index eb21b19..8f201ac 100644 --- a/tui/tui_test.go +++ b/tui/tui_test.go @@ -1016,3 +1016,19 @@ func TestMoreContext(t *testing.T) { t.Error("a click on the hunk header did not show line 20") } } + +// TestCursorLine checks that the line at the cursor gets a tint, and that +// the cursor_line setting turns it off. +func TestCursorLine(t *testing.T) { + m, _ := newTestModel(t) + m = step(t, m, tea.BackgroundColorMsg{Color: color.Black}) + m = press(t, m, "]") + sgr := m.cursorLineSGR() + if sgr == "" || !strings.Contains(m.View().Content, sgr) { + t.Fatal("the cursor line has no tint") + } + m.cfg.CursorLine = false + if m.cursorLineSGR() != "" { + t.Error("cursor_line = false still tints the cursor line") + } +} diff --git a/tui/view.go b/tui/view.go index 113145f..6fd8129 100644 --- a/tui/view.go +++ b/tui/view.go @@ -314,6 +314,7 @@ func (m *model) mainLines(h int) (lines []string, rowAt []int) { if p.text != nil { selSGR = m.textSelectSGR() } + curSGR := m.cursorLineSGR() add := func(l string, row int) { lines, rowAt = append(lines, l), append(rowAt, row) } @@ -334,6 +335,9 @@ func (m *model) mainLines(h int) (lines []string, rowAt []int) { if selSGR != "" { line = p.markSelection(i, selSGR) } + if curSGR != "" && p.head(i) == p.cur { + line = m.cursorLine(line, curSGR) + } add(m.rowMark(i, t, lo, hi)+line, i) if t != nil && p.end(i) == i { addBelow(m.commentsBelow(t)) @@ -345,6 +349,28 @@ func (m *model) mainLines(h int) (lines []string, rowAt []int) { return lines, rowAt } +// cursorLineSGR returns the sequence that tints the line at the cursor, or +// "" if the line gets no tint: the setting is off, the tab has no cursor, +// or the terminal does not tell its background. +func (m *model) cursorLineSGR() string { + if !m.cfg.CursorLine || m.tab.document() || m.bg == nil { + return "" + } + tint := lipgloss.Lighten(m.bg, 0.08) + if !m.dark { + tint = lipgloss.Darken(m.bg, 0.06) + } + return ansi.NewStyle().BackgroundColor(tint).String() +} + +// cursorLine tints line, a line at the cursor, with sgr to the width of +// the code. The cells that have a background of their own, such as an +// added line or a selection, keep it. +func (m *model) cursorLine(line, sgr string) string { + pad := strings.Repeat(" ", max(m.codeWidth()-ansi.StringWidth(line), 0)) + return underSGR(line, sgr) + sgr + pad + ansi.ResetStyle +} + // emptyNote returns the text that shows instead of an empty pane, or "". func (m *model) emptyNote() string { p := m.cur() From b2e37bd9ec2943611f659e7467745efb99d092e5 Mon Sep 17 00:00:00 2001 From: Kenichiro Goto Date: Sun, 8 Nov 2026 20:35:02 +0900 Subject: [PATCH 05/11] tui: find in the file or the file list without hiding them / opens a find bar in the footer in place of the search overlay. As the user types, the cursor moves to the first match and the matches are painted, so the diff stays in view. When the file list has the focus, the find looks at the names of the files and selects the first match, and the files that do not match stay in the list. Enter keeps the find for n and N; esc goes back to where it started. The search of all files and code moves to ctrl+p. --- README.md | 2 + tui/find.go | 218 +++++++++++++++++++++++++++++++++++++++++++++++ tui/keys.go | 6 +- tui/model.go | 17 +++- tui/mouse.go | 3 + tui/nav.go | 50 ++--------- tui/overlay.go | 6 +- tui/selection.go | 9 +- tui/tui_test.go | 31 +++++++ tui/view.go | 9 ++ 10 files changed, 289 insertions(+), 62 deletions(-) create mode 100644 tui/find.go diff --git a/README.md b/README.md index 8054a2e..2b58d47 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,8 @@ are gone, rexdiff marks the comment as stale. | `]` `[` | next or previous change | | `+` `-` | more or fewer unchanged lines around each change (or click `↕`) | | `f` `F` | next or previous file | +| `/` | find in the file, or by name when the file list has the focus (`n` `N` step) | +| `ctrl+p` | search all files and code | | `c` | comment | | `s` | send the comments to the agent | | `y` | copy the selected text, or the comments | diff --git a/tui/find.go b/tui/find.go new file mode 100644 index 0000000..a4c5f0a --- /dev/null +++ b/tui/find.go @@ -0,0 +1,218 @@ +package tui + +// This file finds text as the user types it in the find bar of the footer. +// The pane and the file list stay on the screen: the cursor moves to the +// first match and the matches are painted. In the main pane, the find looks +// at the code. When the file list has the focus, it looks at the names of +// the files and selects the first one that matches. + +import ( + "fmt" + "slices" + "strings" + + "charm.land/bubbles/v2/key" + tea "charm.land/bubbletea/v2" + "github.com/charmbracelet/x/ansi" + + "github.com/frinfo702/rexdiff/diff" +) + +// findSGR marks a match: black on yellow, from the terminal palette. +var findSGR = ansi.NewStyle().ForegroundColor(ansi.Black).BackgroundColor(ansi.Yellow).String() + +// startFind opens the find bar. The find looks in the file list if the +// list shows and has the focus, else in the main pane. +func (m *model) startFind() { + list := m.focusList && m.listWidth() > 0 && !m.tab.document() + from := m.cur().cur + if list { + from = m.listSel() + } + m.find = findState{list: list, from: from} + m.findBar.Reset() + m.findBar.Focus() + m.mode = modeFind +} + +// updateFind handles a key while the find bar is open. Enter keeps the +// find, so that n and N step through its matches. Esc goes back to where +// the find started. +func (m *model) updateFind(msg tea.KeyPressMsg) tea.Cmd { + switch { + case key.Matches(msg, m.keys.Save): + m.mode = modeNormal + if !m.find.active() { + m.find = findState{} + } + return nil + case key.Matches(msg, m.keys.Cancel): + m.mode = modeNormal + f := m.find + m.find = findState{} + if f.list { + m.pickFile(f.from) + } else { + m.cur().cur = f.from + } + m.ensureVisible() + return nil + } + before := m.findBar.Value() + var cmd tea.Cmd + m.findBar, cmd = m.findBar.Update(msg) + if q := m.findBar.Value(); q != before { + m.runFind(q) + m.ensureVisible() + } + return cmd +} + +// runFind finds q, without case, from where the find started. It moves the +// cursor, or the selection of the list, to the first match at or after +// the start, or back to the start if nothing matches. +func (m *model) runFind(q string) { + f := &m.find + f.query, f.hits, f.i = q, nil, 0 + if q == "" { + m.moveToFind(f.from) + return + } + lq := strings.ToLower(q) + if f.list { + for i := range m.listLen() { + if strings.Contains(strings.ToLower(m.listPath(i)), lq) { + f.hits = append(f.hits, i) + } + } + } else { + p := m.cur() + for i := range p.lines { + if !strings.Contains(strings.ToLower(p.searchText(i)), lq) { + continue + } + // The rows of a wrapped line make one hit. + if h := p.head(i); len(f.hits) == 0 || f.hits[len(f.hits)-1] != h { + f.hits = append(f.hits, h) + } + } + } + if !f.active() { + m.moveToFind(f.from) + return + } + f.i = max(slices.IndexFunc(f.hits, func(h int) bool { return h >= f.from }), 0) + m.moveToFind(f.hits[f.i]) +} + +// stepFind moves to the next (d = 1) or the previous (d = -1) match of the +// find. It wraps around. +func (m *model) stepFind(d int) { + f := &m.find + // A reload can make the pane or the list shorter than the matches. + n := len(m.cur().lines) + if f.list { + n = m.listLen() + } + f.hits = slices.DeleteFunc(f.hits, func(h int) bool { return h >= n }) + if len(f.hits) == 0 { + m.find = findState{} + return + } + f.i = (min(f.i, len(f.hits)-1) + d + len(f.hits)) % len(f.hits) + m.moveToFind(f.hits[f.i]) +} + +// moveToFind moves the cursor to row i of the pane, or selects file i of +// the list. +func (m *model) moveToFind(i int) { + if !m.find.list { + m.cur().cur = i + return + } + if i != m.listSel() { + m.pickFile(i) + } +} + +// findCount tells which match of the find the cursor is on, for the find +// bar. +func (m *model) findCount() string { + switch f := m.find; { + case f.query == "": + return "" + case !f.active(): + return "no match" + default: + return fmt.Sprintf("%d/%d", f.i+1, len(f.hits)) + } +} + +// listPath returns the path of file i of the file list of the current tab. +func (m *model) listPath(i int) string { + switch m.tab { + case tabFiles: + return m.allFiles[i].Path + case tabGuide: + return m.guideFiles()[i].path + } + return m.files[i].Path +} + +// searchText returns line i of p as plain text, with the line numbers of a +// diff blanked, so that a find matches only the code. The text has the +// cells of the line. +func (p *pane) searchText(i int) string { + s := ansi.Strip(p.lines[i]) + if p.diff == nil || !p.hasCode(i) { + return s + } + oldLo, oldHi := p.diff.CodeRange(diff.SideOld) + newLo, _ := p.diff.CodeRange(diff.SideNew) + s = blankCells(s, 0, oldLo) + if oldHi > 0 { // the split layout: the new line numbers are in the middle + s = blankCells(s, oldHi, newLo) + } + return s +} + +// blankCells replaces the cells [lo, hi) of the plain text s with spaces. +func blankCells(s string, lo, hi int) string { + w := ansi.StringWidth(s) + lo, hi = min(lo, w), min(hi, w) + if lo >= hi { + return s + } + return ansi.Cut(s, 0, lo) + strings.Repeat(" ", hi-lo) + ansi.Cut(s, hi, w) +} + +// paintMatches marks each match of q in line. text is the plain text of +// line, with the same cells, where the find looks for q. +func paintMatches(line, text, q string) string { + lt, lq := strings.ToLower(text), strings.ToLower(q) + for at := 0; ; { + i := strings.Index(lt[at:], lq) + if i < 0 || lq == "" { + return line + } + i += at + start := ansi.StringWidth(lt[:i]) + line = paintCells(line, start, start+ansi.StringWidth(lq), findSGR) + at = i + len(lq) + } +} + +// paintCells returns line with the cells [start, end) on sgr. The cells +// after them keep their own style only from their next escape sequence. +func paintCells(line string, start, end int, sgr string) string { + w := ansi.StringWidth(line) + end = min(end, w) + if start >= end { + return line + } + out := ansi.Cut(line, 0, start) + carrySGR(ansi.Cut(line, start, end), sgr) + ansi.ResetStyle + if end < w { + out += ansi.Cut(line, end, w) + } + return out +} diff --git a/tui/keys.go b/tui/keys.go index 7e386e7..7c3053d 100644 --- a/tui/keys.go +++ b/tui/keys.go @@ -94,8 +94,8 @@ func defaultKeys() keyMap { Send: bind([]string{"s", "S"}, "s", "send to agent"), Copy: bind([]string{"y", "Y"}, "y", "copy text or comments"), - Search: bind([]string{"/"}, "/", "search files & code"), - Find: bind([]string{"ctrl+f"}, "ctrl+f", "find in file"), + Search: bind([]string{"ctrl+p"}, "ctrl+p", "search all files & code"), + Find: bind([]string{"/", "ctrl+f"}, "/", "find in file (in list: names)"), GotoLine: bind([]string{":"}, ":", "go to line"), Rendered: bind([]string{"m"}, "m", "rendered markdown"), Split: bind([]string{"|"}, "|", "side by side"), @@ -249,6 +249,8 @@ func (h helpKeys) ShortHelp() []key.Binding { switch { case h.mode == modeComment: return []key.Binding{k.Save, k.Newline, k.Cancel} + case h.mode == modeFind: + return []key.Binding{hint(k.Save, "enter", "keep"), hint(k.Cancel, "esc", "go back")} case h.finding: return []key.Binding{ hint(k.FindNext, "n/N", "next/prev match"), diff --git a/tui/model.go b/tui/model.go index 2e9be0d..c83bf91 100644 --- a/tui/model.go +++ b/tui/model.go @@ -10,6 +10,7 @@ import ( "charm.land/bubbles/v2/help" "charm.land/bubbles/v2/textarea" + "charm.land/bubbles/v2/textinput" tea "charm.land/bubbletea/v2" uv "github.com/charmbracelet/ultraviolet" @@ -68,6 +69,7 @@ const ( modeNormal mode = iota modeComment modeOverlay + modeFind // the find bar in the footer takes the keys ) // pane is one view that scrolls and takes comments: the rendered lines and @@ -155,11 +157,14 @@ type turnState struct { at time.Time // the start of the turn } -// findState is the result of a find in the current pane. +// findState is the result of a find in the current pane, or in the file +// list if list is true. type findState struct { query string - hits []int // the first rows of the lines that match, in order + hits []int // the first rows of the lines, or the files, that match, in order i int // the hit at the cursor + list bool + from int // the row or the file where the find started; esc goes back to it } // active tells if the find has hits, so that n and N step through them. @@ -259,6 +264,7 @@ type model struct { mode mode overlay *overlay find findState + findBar textinput.Model drag dragState help help.Model @@ -309,6 +315,8 @@ func newModel(ctx context.Context, o Options, cfg config) model { } m.changes.anchor, m.viewer.anchor, m.prPane.anchor = -1, -1, -1 m.overPane.anchor, m.guidePane.anchor = -1, -1 + m.findBar = textinput.New() + m.findBar.Prompt = "/ " m.cfg = cfg m.keys = defaultKeys() m.keys.applyConfig(cfg.Keybindings) @@ -604,6 +612,8 @@ func (m *model) onKey(msg tea.KeyPressMsg) tea.Cmd { return m.updateComment(msg) case modeOverlay: return m.updateOverlay(msg) + case modeFind: + return m.updateFind(msg) } return m.updateNormal(msg) } @@ -635,6 +645,9 @@ func (m *model) onPaste(text string) tea.Cmd { switch { case m.mode == modeComment: m.editor.InsertString(text) + case m.mode == modeFind: + m.findBar.SetValue(m.findBar.Value() + text) + m.runFind(m.findBar.Value()) case m.mode == modeOverlay && m.overlay != nil && m.overlay.hasInput(): m.overlay.input.SetValue(m.overlay.input.Value() + text) return m.inputChanged() diff --git a/tui/mouse.go b/tui/mouse.go index a4b0dd1..ca2b1d7 100644 --- a/tui/mouse.go +++ b/tui/mouse.go @@ -23,6 +23,9 @@ func (m *model) onClick(mouse tea.Mouse) tea.Cmd { // A click does nothing while the comment box is open. return nil } + if m.mode == modeFind { + m.mode = modeNormal // keep the find, as enter does + } m.cur().text = nil if mouse.Y == 0 { _, spans := m.header() diff --git a/tui/nav.go b/tui/nav.go index bea7ed5..021b146 100644 --- a/tui/nav.go +++ b/tui/nav.go @@ -8,7 +8,6 @@ import ( "charm.land/bubbles/v2/key" tea "charm.land/bubbletea/v2" - "github.com/charmbracelet/x/ansi" "github.com/frinfo702/rexdiff/diff" "github.com/frinfo702/rexdiff/vcs" @@ -226,7 +225,7 @@ func (m *model) viewKey(msg tea.KeyPressMsg) (tea.Cmd, bool) { m.loadFiles() m.openSearch() case key.Matches(msg, k.Find): - m.openInput(overlayFind, "find in file", m.find.query) + m.startFind() case key.Matches(msg, k.GotoLine): m.openInput(overlayGoto, "go to line (:0 first, :$ last)", "") case key.Matches(msg, k.Rendered): @@ -381,7 +380,10 @@ func (m *model) pickFile(i int) { m.guidePane.toStart() m.renderGuide() } - m.find, m.drag = findState{}, dragState{} + if !m.find.list { // a find in the list moves through the list + m.find = findState{} + } + m.drag = dragState{} } // stepChange moves the cursor to the next (d = 1) or the previous (d = -1) @@ -477,48 +479,6 @@ func (p *pane) rowOf(s diff.Side, line int) int { return slices.IndexFunc(p.rows, func(r diff.Row) bool { return r.Line(s) == line }) } -// stepFind moves the cursor to the next (d = 1) or the previous (d = -1) -// hit of the find. It wraps around. -func (m *model) stepFind(d int) { - f, p := &m.find, m.cur() - // A reload can make the pane shorter than the rows that matched. - f.hits = slices.DeleteFunc(f.hits, func(h int) bool { return h >= len(p.lines) }) - if len(f.hits) == 0 { - m.find = findState{} - return - } - f.i = (min(f.i, len(f.hits)-1) + d + len(f.hits)) % len(f.hits) - p.cur = f.hits[f.i] -} - -// runFind finds q in the lines of the current pane, without case. It moves -// the cursor to the first hit at or below it. -func (m *model) runFind(q string) { - p := m.cur() - m.find = findState{query: q} - if q == "" { - return - } - lq := strings.ToLower(q) - for i, l := range p.lines { - if !strings.Contains(strings.ToLower(ansi.Strip(l)), lq) { - continue - } - // The rows of a wrapped line make one hit. - hits := m.find.hits - if h := p.head(i); len(hits) == 0 || hits[len(hits)-1] != h { - m.find.hits = append(hits, h) - } - } - if !m.find.active() { - m.flash("no match for " + q) - return - } - atCursor := func(h int) bool { return h >= p.cur } - m.find.i = max(slices.IndexFunc(m.find.hits, atCursor), 0) - p.cur = m.find.hits[m.find.i] -} - // gotoLine moves the cursor to the line number in s: "0" is the first // row, "$" the last row. func (m *model) gotoLine(s string) { diff --git a/tui/overlay.go b/tui/overlay.go index d5301a8..df9d6db 100644 --- a/tui/overlay.go +++ b/tui/overlay.go @@ -26,7 +26,6 @@ const ( overlayComments overlaySearch overlayGoto - overlayFind overlayQuit ) @@ -385,9 +384,6 @@ func (m *model) chooseOverlay() tea.Cmd { case overlayGoto: m.closeOverlay() m.gotoLine(ov.input.Value()) - case overlayFind: - m.closeOverlay() - m.runFind(ov.input.Value()) case overlaySearch: m.closeOverlay() if it != nil { @@ -518,7 +514,7 @@ func (m *model) overlayRows(inner int) (rows []string, start int) { } rows = append(rows, row) } - if len(ov.shown) == 0 && ov.kind != overlayGoto && ov.kind != overlayFind { + if len(ov.shown) == 0 && ov.kind != overlayGoto { rows = append(rows, dimStyle.Render(" nothing matches")) } return rows, start diff --git a/tui/selection.go b/tui/selection.go index 2e507c1..0c5bf19 100644 --- a/tui/selection.go +++ b/tui/selection.go @@ -120,14 +120,7 @@ func (p *pane) markSelection(i int, sgr string) string { return line } start, end := p.selectionCols(i, lo, hi) - if start >= end { - return line - } - out := ansi.Cut(line, 0, start) + carrySGR(ansi.Cut(line, start, end), sgr) + ansi.ResetStyle - if end < ansi.StringWidth(line) { - out += ansi.Cut(line, end, ansi.StringWidth(line)) - } - return out + return paintCells(line, start, end, sgr) } // carrySGR repeats sgr after each escape sequence of s. A reset in the diff --git a/tui/tui_test.go b/tui/tui_test.go index 8f201ac..9694eb4 100644 --- a/tui/tui_test.go +++ b/tui/tui_test.go @@ -1032,3 +1032,34 @@ func TestCursorLine(t *testing.T) { t.Error("cursor_line = false still tints the cursor line") } } + +// TestFind checks that / finds in the diff as the user types, with the file +// list still on the screen, and that in the file list it finds by name. +func TestFind(t *testing.T) { + m, _ := newTestModel(t) + m = press(t, m, "/", "x", " ", ":") + p := &m.changes + if m.mode != modeFind || !strings.Contains(ansi.Strip(p.lines[p.cur]), "x := 2") { + t.Fatalf("/x : did not move to the match: mode %v, line %q", m.mode, ansi.Strip(p.lines[p.cur])) + } + if v := view(m); !strings.Contains(v, "Changes (1)") || !strings.Contains(v, "/ x :") { + t.Errorf("the find hides the list or has no bar:\n%s", v) + } + if m = press(t, m, "enter"); m.mode != modeNormal || !m.find.active() { + t.Errorf("enter: mode %v, find active %v", m.mode, m.find.active()) + } + from := p.cur + m = press(t, m, "esc", "home", "/", "q", "q", "q", "esc") + if p.cur != 0 || m.find.active() { + t.Errorf("esc after no match: cursor %d (was at %d before home), find %v", p.cur, from, m.find.active()) + } + + // In the list, the find selects a file by its name. + m = press(t, m, "4", "tab", "/", "b", ".") + if got := m.allFiles[m.allSel].Path; got != "b.go" { + t.Errorf("/b. in the list selected %q, want b.go", got) + } + if !strings.Contains(view(m), "a.go") { + t.Error("the find in the list hides the files that do not match") + } +} diff --git a/tui/view.go b/tui/view.go index 6fd8129..d6bf1b1 100644 --- a/tui/view.go +++ b/tui/view.go @@ -220,6 +220,9 @@ func (m *model) listLines(h int) []string { sel := m.listSel() for i := m.listStart(h); i < n && len(out) < h; i++ { r := row(i) + if m.find.list && m.find.query != "" { + r = paintMatches(r, ansi.Strip(r), m.find.query) + } if i == sel { r = m.selectedRow(r, w) } @@ -335,6 +338,9 @@ func (m *model) mainLines(h int) (lines []string, rowAt []int) { if selSGR != "" { line = p.markSelection(i, selSGR) } + if m.find.query != "" && !m.find.list { + line = paintMatches(line, p.searchText(i), m.find.query) + } if curSGR != "" && p.head(i) == p.cur { line = m.cursorLine(line, curSGR) } @@ -404,6 +410,7 @@ func (m *model) highlighted() (lo, hi int) { func (m *model) rowMark(i int, t *targetLine, lo, hi int) string { p := m.cur() _, hit := slices.BinarySearch(m.find.hits, i) // the hits are in order + hit = hit && !m.find.list switch { case i == p.cur && !m.tab.document(): return cursorStyle.Render("▶ ") @@ -545,6 +552,8 @@ func (m *model) footerLine() string { m.help.SetWidth(m.w) var badge string switch { + case m.mode == modeFind: + badge = m.findBar.View() + " " + findStyle.Render(m.findCount()) case m.status != "": badge = cursorStyle.Render(m.status) case m.release != nil: From 744ca609039f73c2d5fe6a0d41aeb019887d0b16 Mon Sep 17 00:00:00 2001 From: Kenichiro Goto Date: Sun, 8 Nov 2026 20:35:45 +0900 Subject: [PATCH 06/11] tui: select a word with a double click A second click on the same cell of the code within 400 ms selects the word under the pointer, its letters, digits, and underscores, and copies it, as a release after a drag does. --- README.md | 2 +- tui/model.go | 8 ++++++++ tui/mouse.go | 12 ++++++++++++ tui/selection.go | 35 +++++++++++++++++++++++++++++++++++ tui/tui_test.go | 19 +++++++++++++++++++ 5 files changed, 75 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 2b58d47..4671bd4 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ it says so when Rex is not installed. The viewer itself runs without Rex. command palette. Press it again to close rexdiff. - Comment: move to a line and press `c`. For a range, press `v` or drag over the line numbers. -- Copy: drag over the code to select it. Release copies the selection, and +- Copy: drag over the code to select it, or double-click a word. Release copies the selection, and `y` copies it again. `esc` clears it. It works in each tab. - Send: press `s`. rexdiff pastes the comments into the agent's input. It does not press Enter. diff --git a/tui/model.go b/tui/model.go index c83bf91..c0e5f33 100644 --- a/tui/model.go +++ b/tui/model.go @@ -180,6 +180,13 @@ type dragState struct { pref diff.Side // the side of the line numbers or the code at the start } +// lastClick is the last press of the left button on the code, to notice a +// double click. +type lastClick struct { + at time.Time + x, y int +} + // draft is the comment that the user writes: a new one, or an edit of the // comment with ID editID. type draft struct { @@ -266,6 +273,7 @@ type model struct { find findState findBar textinput.Model drag dragState + click lastClick help help.Model status string diff --git a/tui/mouse.go b/tui/mouse.go index ca2b1d7..cf672da 100644 --- a/tui/mouse.go +++ b/tui/mouse.go @@ -5,6 +5,8 @@ package tui // Click a file or a tab to open it. import ( + "time" + tea "charm.land/bubbletea/v2" "charm.land/lipgloss/v2" @@ -75,10 +77,20 @@ func (m *model) onClick(mouse tea.Mouse) tea.Cmd { if !onNumber { pt := p.selectAt(rowAt[y], x) p.text = &textSelection{start: pt, end: pt, side: side} + last := m.click + m.click = lastClick{time.Now(), mouse.X, mouse.Y} + if m.click.at.Sub(last.at) < doubleClick && last.x == mouse.X && last.y == mouse.Y { + m.drag = dragState{} // the release must not move the end + p.text = p.wordAt(pt, side) + return m.copyTextSelection() + } } return nil } +// doubleClick is the longest time between the two clicks of a double click. +const doubleClick = 400 * time.Millisecond + // hunkHeader tells if row i is the line above a hunk of a diff. Row 0 is // the file header. func (p *pane) hunkHeader(i int) bool { diff --git a/tui/selection.go b/tui/selection.go index 0c5bf19..f67785f 100644 --- a/tui/selection.go +++ b/tui/selection.go @@ -6,8 +6,10 @@ package tui // again and esc can clear it. import ( + "slices" "strconv" "strings" + "unicode" "charm.land/bubbletea/v2" "charm.land/lipgloss/v2" @@ -50,6 +52,39 @@ func (p *pane) selectAt(i, x int) textPoint { return textPoint{row: i, col: min(max(x, 0), max(w-1, 0))} } +// wordAt returns the selection of the word at pt: the letters, the digits, +// and the underscores around it. A cell that is not in a word selects only +// its character. +func (p *pane) wordAt(pt textPoint, side diff.Side) *textSelection { + type cell struct { + col, w int + word bool + } + var cells []cell + col := 0 + for _, r := range ansi.Strip(p.lines[pt.row]) { + w := max(ansi.StringWidth(string(r)), 1) + cells = append(cells, cell{col, w, unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_'}) + col += w + } + k := slices.IndexFunc(cells, func(c cell) bool { return pt.col < c.col+c.w }) + if k < 0 { + return &textSelection{start: pt, end: pt, side: side} + } + lo, hi := k, k + for cells[k].word && lo > 0 && cells[lo-1].word { + lo-- + } + for cells[k].word && hi+1 < len(cells) && cells[hi+1].word { + hi++ + } + return &textSelection{ + start: textPoint{pt.row, cells[lo].col}, + end: textPoint{pt.row, cells[hi].col + cells[hi].w - 1}, + side: side, + } +} + // selectedText returns the text that p.text selects. It leaves out the // spaces at the end of each line, and in a diff it leaves out the line // numbers and the marks. A wrapped line gives one line, as the source does. diff --git a/tui/tui_test.go b/tui/tui_test.go index 9694eb4..1ee42d0 100644 --- a/tui/tui_test.go +++ b/tui/tui_test.go @@ -1063,3 +1063,22 @@ func TestFind(t *testing.T) { t.Error("the find in the list hides the files that do not match") } } + +// TestDoubleClickWord checks that a double click on the code selects and +// copies the word under the pointer. +func TestDoubleClickWord(t *testing.T) { + m, _ := newTestModel(t) + p := &m.changes + i := slices.IndexFunc(p.lines, func(l string) bool { return strings.Contains(ansi.Strip(l), "return x") }) + plain := ansi.Strip(p.lines[i]) + x := m.mainX() + gutter + ansi.StringWidth(plain[:strings.Index(plain, "return x")]) + 2 + y := screenY(t, m, i) + m = click(t, m, x, y) + m = click(t, m, x, y) + if got := m.changes.selectedText(); got != "return" { + t.Errorf("double click selected %q, want \"return\"", got) + } + if m.status != "copied 6 chars" { + t.Errorf("status %q, want the copy", m.status) + } +} From 0a00c9e61e84c4241de3a0765ce8f7ceb3c98fe5 Mon Sep 17 00:00:00 2001 From: Kenichiro Goto Date: Sun, 8 Nov 2026 20:41:14 +0900 Subject: [PATCH 07/11] tui: tint the cursor line on changed lines too The tint of the cursor line skipped the cells with a background of their own, so an added or a deleted line at the cursor showed no tint. Those cells now get their own background shaded, so the line keeps its green or red and still shows the cursor. --- tui/selection.go | 42 ++++++++++++++++++++++++++++++++++++++---- tui/selection_test.go | 11 +++++++---- tui/view.go | 16 +++++++++++----- 3 files changed, 56 insertions(+), 13 deletions(-) diff --git a/tui/selection.go b/tui/selection.go index f67785f..1538700 100644 --- a/tui/selection.go +++ b/tui/selection.go @@ -6,6 +6,7 @@ package tui // again and esc can clear it. import ( + "image/color" "slices" "strconv" "strings" @@ -180,8 +181,9 @@ func carrySGR(s, sgr string) string { } // underSGR puts sgr under the cells of s that have no background of their -// own, so that sgr shows only where s shows the terminal background. -func underSGR(s, sgr string) string { +// own, so that sgr shows only where s shows the terminal background. A cell +// with a background in RGB of its own gets it through shade. +func underSGR(s, sgr string, shade func(color.Color) color.Color) string { var b strings.Builder b.WriteString(sgr) own := false // the text sets its own background now @@ -194,8 +196,11 @@ func underSGR(s, sgr string) string { } b.WriteString(seq) if width == 0 && strings.HasPrefix(seq, "\x1b[") && strings.HasSuffix(seq, "m") { - own = setsBackground(seq[2:len(seq)-1], own) - if !own { + params := seq[2 : len(seq)-1] + own = setsBackground(params, own) + if c, ok := rgbBackground(params); own && ok { + b.WriteString(ansi.NewStyle().BackgroundColor(shade(c)).String()) + } else if !own { b.WriteString(sgr) } } @@ -236,6 +241,35 @@ func setsBackground(params string, own bool) bool { return own } +// rgbBackground returns the RGB background that the SGR parameters params +// set, if they set one. +func rgbBackground(params string) (c color.RGBA, ok bool) { + ps := strings.Split(params, ";") + for i := 0; i < len(ps); i++ { + switch ps[i] { + case "38", "58": // a colour of the text or the underline + if i+1 < len(ps) && ps[i+1] == "5" { + i += 2 + } else if i+1 < len(ps) && ps[i+1] == "2" { + i += 4 + } + case "48": + if i+4 < len(ps) && ps[i+1] == "2" { + var v [3]uint8 + for k := range v { + n, err := strconv.Atoi(ps[i+2+k]) + if err != nil || n < 0 || n > 255 { + return color.RGBA{}, false + } + v[k] = uint8(n) + } + c, ok = color.RGBA{v[0], v[1], v[2], 255}, true + } + } + } + return c, ok +} + // textSelectSGR returns the sequence that marks a selection. It tints the // background, or reverses the colours if the terminal does not tell its // background. diff --git a/tui/selection_test.go b/tui/selection_test.go index c404974..fe32df3 100644 --- a/tui/selection_test.go +++ b/tui/selection_test.go @@ -2,6 +2,7 @@ package tui import ( "fmt" + "image/color" "strings" "testing" @@ -171,13 +172,15 @@ func TestMarkSelection(t *testing.T) { } } -// TestUnderSGR checks that the tint of the cursor line shows only on the -// cells that have no background of their own. +// TestUnderSGR checks that the tint of the cursor line shows on the cells +// with no background of their own, and shades the cells that have one. func TestUnderSGR(t *testing.T) { const tint = "\x1b[48;5;1m" green := "\x1b[38;2;48;0;0;48;2;0;9;0m" // a foreground of 48 is not a background - got := underSGR("a"+green+"b\x1b[mc\x1b[38;2;48;1;1md", tint) - want := tint + "a" + green + "b\x1b[m" + tint + "c\x1b[38;2;48;1;1m" + tint + "d" + white := func(color.Color) color.Color { return color.White } + got := underSGR("a"+green+"b\x1b[mc\x1b[38;2;48;1;1md", tint, white) + shaded := "\x1b[48;2;255;255;255m" // the green background, shaded + want := tint + "a" + green + shaded + "b\x1b[m" + tint + "c\x1b[38;2;48;1;1m" + tint + "d" if got != want { t.Errorf("underSGR:\n got %q\nwant %q", got, want) } diff --git a/tui/view.go b/tui/view.go index d6bf1b1..189504e 100644 --- a/tui/view.go +++ b/tui/view.go @@ -2,6 +2,7 @@ package tui import ( "fmt" + "image/color" "path" "slices" "strings" @@ -362,19 +363,24 @@ func (m *model) cursorLineSGR() string { if !m.cfg.CursorLine || m.tab.document() || m.bg == nil { return "" } - tint := lipgloss.Lighten(m.bg, 0.08) + return ansi.NewStyle().BackgroundColor(m.shade(m.bg)).String() +} + +// shade returns c a little lighter on a dark terminal, and a little darker +// on a light one: the tint of the cursor line. +func (m *model) shade(c color.Color) color.Color { if !m.dark { - tint = lipgloss.Darken(m.bg, 0.06) + return lipgloss.Darken(c, 0.06) } - return ansi.NewStyle().BackgroundColor(tint).String() + return lipgloss.Lighten(c, 0.08) } // cursorLine tints line, a line at the cursor, with sgr to the width of // the code. The cells that have a background of their own, such as an -// added line or a selection, keep it. +// added line, get their background shaded, so that they keep their hue. func (m *model) cursorLine(line, sgr string) string { pad := strings.Repeat(" ", max(m.codeWidth()-ansi.StringWidth(line), 0)) - return underSGR(line, sgr) + sgr + pad + ansi.ResetStyle + return underSGR(line, sgr, m.shade) + sgr + pad + ansi.ResetStyle } // emptyNote returns the text that shows instead of an empty pane, or "". From cc878ce90008b974d0882f203d3f012aabcd6335 Mon Sep 17 00:00:00 2001 From: Kenichiro Goto Date: Sun, 8 Nov 2026 20:49:39 +0900 Subject: [PATCH 08/11] tui: find in the source lines of a diff The find stripped the escape sequences of each rendered line and blanked its line numbers at each key, which took about 60 ms on 20,000 lines. It now looks at the source lines that the rows number, in lower case once per render, and takes about 2 ms. It also sees the part of a line that the screen cuts off. Rendered markdown and the PR still match by their text. --- tui/find.go | 34 ++++++++++++++++++++++++++++------ tui/model.go | 6 +++++- tui/render.go | 2 ++ tui/tui_test.go | 11 +++++++++++ 4 files changed, 46 insertions(+), 7 deletions(-) diff --git a/tui/find.go b/tui/find.go index a4c5f0a..b13721d 100644 --- a/tui/find.go +++ b/tui/find.go @@ -88,12 +88,9 @@ func (m *model) runFind(q string) { } else { p := m.cur() for i := range p.lines { - if !strings.Contains(strings.ToLower(p.searchText(i)), lq) { - continue - } - // The rows of a wrapped line make one hit. - if h := p.head(i); len(f.hits) == 0 || f.hits[len(f.hits)-1] != h { - f.hits = append(f.hits, h) + // The rows of a wrapped line make one hit, on its first row. + if !p.cont(i) && p.matches(i, lq) { + f.hits = append(f.hits, i) } } } @@ -159,6 +156,31 @@ func (m *model) listPath(i int) string { return m.files[i].Path } +// matches tells if the line that row i shows has lq, a query in lower +// case. A row of a diff matches by its source lines, so that the find sees +// the parts of a line that the screen cuts off. A row of rendered text +// matches by its text. +func (p *pane) matches(i int, lq string) bool { + if p.src == nil { + return strings.Contains(strings.ToLower(p.searchText(i)), lq) + } + if p.lower == nil { + p.lower = new([2][]string) + for s, lines := range p.src { + for _, l := range lines { + p.lower[s] = append(p.lower[s], strings.ToLower(l)) + } + } + } + r := p.rows[i] + for s, n := range [2]int{r.Old, r.New} { + if n > 0 && n <= len(p.lower[s]) && strings.Contains(p.lower[s][n-1], lq) { + return true + } + } + return false +} + // searchText returns line i of p as plain text, with the line numbers of a // diff blanked, so that a find matches only the code. The text has the // cells of the line. diff --git a/tui/model.go b/tui/model.go index c0e5f33..002e931 100644 --- a/tui/model.go +++ b/tui/model.go @@ -86,6 +86,10 @@ type pane struct { xoff int // the sideways scroll, in columns more int // the unchanged lines around a change, beyond the default note string // shown instead of the lines, if there are no lines + // src has the old and the new source lines that the rows number, or + // nil if the rows show no source lines. lower has them in lower case, + // for a find; it is made at the first find. + src, lower *[2][]string // free is true after the wheel moves the view. Then the cursor can // be off the screen until the next key or click. free bool @@ -95,7 +99,7 @@ type pane struct { // comment selection in the new lines. A text selection does not survive a // new render, because its cells can move. func (p *pane) set(lines []string, rows []diff.Row) { - p.lines, p.rows, p.diff, p.text = lines, rows, nil, nil + p.lines, p.rows, p.diff, p.text, p.src, p.lower = lines, rows, nil, nil, nil, nil p.cur = min(p.cur, max(len(lines)-1, 0)) p.top = min(p.top, max(len(lines)-1, 0)) if p.anchor >= len(rows) { // the file is shorter than before diff --git a/tui/render.go b/tui/render.go index 79b7e7c..ae356f1 100644 --- a/tui/render.go +++ b/tui/render.go @@ -158,6 +158,7 @@ func (m *model) renderChanged(p *pane, f *changed) { m.setMarkdown(p, f.New) default: p.setDiff(diff.Render(f.Path, f.Old, f.New, m.diffOptions(p))) + p.src = &[2][]string{diff.Lines(f.Old), diff.Lines(f.New)} } p.addHeader(m.fileHeader(f)) } @@ -246,6 +247,7 @@ func (m *model) refreshViewer() { m.setMarkdown(p, content) default: p.setDiff(diff.RenderFile(path, content, m.diffOptions(p))) + p.src = &[2][]string{nil, diff.Lines(content)} } } diff --git a/tui/tui_test.go b/tui/tui_test.go index 1ee42d0..b0c1dbc 100644 --- a/tui/tui_test.go +++ b/tui/tui_test.go @@ -1082,3 +1082,14 @@ func TestDoubleClickWord(t *testing.T) { t.Errorf("status %q, want the copy", m.status) } } + +// TestFindPastScreen checks that the find sees the part of a line that the +// screen cuts off. +func TestFindPastScreen(t *testing.T) { + m, dir := newTestModel(t) + write(t, dir, "a.go", "package a\n\n// "+strings.Repeat("x", 300)+" needle\n") + m.reload() + if m = press(t, m, "/", "n", "e", "e", "d", "l", "e"); !m.find.active() { + t.Error("the find does not see a match past the edge of the screen") + } +} From ed310ac229613046b6aadcb211336d22eb55aba9 Mon Sep 17 00:00:00 2001 From: Kenichiro Goto Date: Sun, 8 Nov 2026 20:50:22 +0900 Subject: [PATCH 09/11] tui: narrow a find to its hits as the user types on A query that adds to the last one matches only where the last one did, so the find looks only at those hits. A shorter query, a new render of the pane, or a change of the list looks at all the lines again. --- tui/find.go | 33 +++++++++++++++++++++------------ tui/model.go | 3 +++ tui/tui_test.go | 15 +++++++++++++++ 3 files changed, 39 insertions(+), 12 deletions(-) diff --git a/tui/find.go b/tui/find.go index b13721d..2b48e19 100644 --- a/tui/find.go +++ b/tui/find.go @@ -73,23 +73,32 @@ func (m *model) updateFind(msg tea.KeyPressMsg) tea.Cmd { // the start, or back to the start if nothing matches. func (m *model) runFind(q string) { f := &m.find - f.query, f.hits, f.i = q, nil, 0 + lq, prev := strings.ToLower(q), strings.ToLower(f.query) + p, gen := m.cur(), m.cur().gen + if f.list { + gen = m.listLen() + } + // A longer query matches only where the shorter one did, so a query + // that the user types on looks only at the hits so far. + narrow := prev != "" && strings.HasPrefix(lq, prev) && f.gen == gen + old := f.hits + f.query, f.hits, f.i, f.gen = q, nil, 0, gen if q == "" { m.moveToFind(f.from) return } - lq := strings.ToLower(q) - if f.list { - for i := range m.listLen() { - if strings.Contains(strings.ToLower(m.listPath(i)), lq) { - f.hits = append(f.hits, i) - } - } + match := func(i int) bool { return strings.Contains(strings.ToLower(m.listPath(i)), lq) } + n := m.listLen() + if !f.list { + // The rows of a wrapped line make one hit, on its first row. + match = func(i int) bool { return !p.cont(i) && p.matches(i, lq) } + n = len(p.lines) + } + if narrow { + f.hits = slices.DeleteFunc(old, func(i int) bool { return !match(i) }) } else { - p := m.cur() - for i := range p.lines { - // The rows of a wrapped line make one hit, on its first row. - if !p.cont(i) && p.matches(i, lq) { + for i := range n { + if match(i) { f.hits = append(f.hits, i) } } diff --git a/tui/model.go b/tui/model.go index 002e931..747461a 100644 --- a/tui/model.go +++ b/tui/model.go @@ -90,6 +90,7 @@ type pane struct { // nil if the rows show no source lines. lower has them in lower case, // for a find; it is made at the first find. src, lower *[2][]string + gen int // counts the renders, so that a find knows if its hits are old // free is true after the wheel moves the view. Then the cursor can // be off the screen until the next key or click. free bool @@ -100,6 +101,7 @@ type pane struct { // new render, because its cells can move. func (p *pane) set(lines []string, rows []diff.Row) { p.lines, p.rows, p.diff, p.text, p.src, p.lower = lines, rows, nil, nil, nil, nil + p.gen++ p.cur = min(p.cur, max(len(lines)-1, 0)) p.top = min(p.top, max(len(lines)-1, 0)) if p.anchor >= len(rows) { // the file is shorter than before @@ -169,6 +171,7 @@ type findState struct { i int // the hit at the cursor list bool from int // the row or the file where the find started; esc goes back to it + gen int // the render of the pane, or the length of the list, of the hits } // active tells if the find has hits, so that n and N step through them. diff --git a/tui/tui_test.go b/tui/tui_test.go index b0c1dbc..cb15fd7 100644 --- a/tui/tui_test.go +++ b/tui/tui_test.go @@ -89,6 +89,7 @@ func press(t *testing.T, m model, keys ...string) model { "home": tea.KeyHome, "end": tea.KeyEnd, "tab": tea.KeyTab, + "bksp": tea.KeyBackspace, } for _, k := range keys { code, ok := named[k] @@ -1093,3 +1094,17 @@ func TestFindPastScreen(t *testing.T) { t.Error("the find does not see a match past the edge of the screen") } } + +// TestFindNarrow checks that a longer query looks only at the hits so far, +// and that a shorter one looks at all the lines again. +func TestFindNarrow(t *testing.T) { + m, _ := newTestModel(t) + m = press(t, m, "/", "r", "e") + all := len(m.find.hits) + if m = press(t, m, "z"); m.find.active() { + t.Fatalf("/rez matches %v", m.find.hits) + } + if m = press(t, m, "bksp"); len(m.find.hits) != all || all == 0 { + t.Errorf("backspace to /re: %d hits, want %d", len(m.find.hits), all) + } +} From 28ce8eee9b8d317fb2d93dae75383011e0e20cb8 Mon Sep 17 00:00:00 2001 From: Kenichiro Goto Date: Sun, 8 Nov 2026 20:56:25 +0900 Subject: [PATCH 10/11] tui: paint the matches of a find in one pass paintMatches cut the whole line three times for each match, and measured the text before each match from its start. A one-letter query on lines with twenty matches took 6.8 s to draw a screen. paintSpans now paints all the matches, or a text selection, in one walk of the line, and the screen takes 3 ms. After a span, the line goes on in its own style, where it lost its colours until its next escape sequence before. --- tui/find.go | 75 ++++++++++++++++++++++++++++++--------- tui/selection.go | 23 +----------- tui/selection_test.go | 15 ++++++++ tui/zz_find_bench_test.go | 52 +++++++++++++++++++++++++++ 4 files changed, 127 insertions(+), 38 deletions(-) create mode 100644 tui/zz_find_bench_test.go diff --git a/tui/find.go b/tui/find.go index 2b48e19..aea54a3 100644 --- a/tui/find.go +++ b/tui/find.go @@ -221,29 +221,72 @@ func blankCells(s string, lo, hi int) string { // line, with the same cells, where the find looks for q. func paintMatches(line, text, q string) string { lt, lq := strings.ToLower(text), strings.ToLower(q) + if lq == "" { + return line + } + var spans [][2]int + col := 0 // the cell where lt[at:] starts for at := 0; ; { i := strings.Index(lt[at:], lq) - if i < 0 || lq == "" { - return line + if i < 0 { + break } - i += at - start := ansi.StringWidth(lt[:i]) - line = paintCells(line, start, start+ansi.StringWidth(lq), findSGR) - at = i + len(lq) + col += ansi.StringWidth(lt[at : at+i]) + w := ansi.StringWidth(lq) + spans = append(spans, [2]int{col, col + w}) + col += w + at += i + len(lq) } + return paintSpans(line, spans, findSGR) } -// paintCells returns line with the cells [start, end) on sgr. The cells -// after them keep their own style only from their next escape sequence. -func paintCells(line string, start, end int, sgr string) string { - w := ansi.StringWidth(line) - end = min(end, w) - if start >= end { +// paintSpans returns line with the cells of each span [start, end) on sgr, +// in one pass. spans are in order and do not overlap. After a span, the +// line goes on in its own style. +func paintSpans(line string, spans [][2]int, sgr string) string { + if len(spans) == 0 { return line } - out := ansi.Cut(line, 0, start) + carrySGR(ansi.Cut(line, start, end), sgr) + ansi.ResetStyle - if end < w { - out += ansi.Cut(line, end, w) + var b, style strings.Builder // style: the SGR of the line since its last reset + col, k, in := 0, 0, false + var state byte + for len(line) > 0 { + seq, width, n, next := ansi.DecodeSequence(line, state, nil) + if n <= 0 { + b.WriteString(line) + break + } + line, state = line[n:], next + if seq[0] == ansi.ESC { + b.WriteString(seq) + if strings.HasSuffix(seq, "m") && strings.HasPrefix(seq, "\x1b[") { + if seq == "\x1b[m" || seq == "\x1b[0m" { + style.Reset() + } else { + style.WriteString(seq) + } + if in { // the text must not turn the span off + b.WriteString(sgr) + } + } + continue + } + for k < len(spans) && spans[k][1] <= col { + k++ + } + want := k < len(spans) && col >= spans[k][0] + switch { + case want && !in: + b.WriteString(sgr) + case !want && in: + b.WriteString(ansi.ResetStyle + style.String()) + } + in = want + b.WriteString(seq) + col += width + } + if in { + b.WriteString(ansi.ResetStyle) } - return out + return b.String() } diff --git a/tui/selection.go b/tui/selection.go index 1538700..09100e4 100644 --- a/tui/selection.go +++ b/tui/selection.go @@ -156,28 +156,7 @@ func (p *pane) markSelection(i int, sgr string) string { return line } start, end := p.selectionCols(i, lo, hi) - return paintCells(line, start, end, sgr) -} - -// carrySGR repeats sgr after each escape sequence of s. A reset in the -// text then cannot turn the selection off. -func carrySGR(s, sgr string) string { - var b strings.Builder - b.WriteString(sgr) - var state byte - for len(s) > 0 { - seq, width, n, next := ansi.DecodeSequence(s, state, nil) - if n <= 0 { - b.WriteString(s) - break - } - b.WriteString(seq) - if width == 0 { - b.WriteString(sgr) - } - s, state = s[n:], next - } - return b.String() + return paintSpans(line, [][2]int{{start, end}}, sgr) } // underSGR puts sgr under the cells of s that have no background of their diff --git a/tui/selection_test.go b/tui/selection_test.go index fe32df3..b6d8939 100644 --- a/tui/selection_test.go +++ b/tui/selection_test.go @@ -188,3 +188,18 @@ func TestUnderSGR(t *testing.T) { t.Error("a foreground with a 48 in it counts as a background") } } + +// TestPaintSpans checks that the spans get the mark, that a style in the +// text does not turn a span off, and that the line keeps its own style +// after a span. +func TestPaintSpans(t *testing.T) { + const mark, red = "\x1b[7m", "\x1b[31m" + got := paintSpans(red+"ab"+"\x1b[1m"+"cdé\x1b[m", [][2]int{{1, 3}, {4, 5}}, mark) + want := red + "a" + mark + "b" + "\x1b[1m" + mark + "c" + "\x1b[m" + red + "\x1b[1m" + "d" + mark + "é" + "\x1b[m" + mark + "\x1b[m" + if got != want { + t.Errorf("paintSpans:\n got %q\nwant %q", got, want) + } + if got := paintMatches("Go go", "Go go", "go"); strings.Count(got, findSGR) != 2 { + t.Errorf("paintMatches marks %d matches of go in %q, want 2", strings.Count(got, findSGR), got) + } +} diff --git a/tui/zz_find_bench_test.go b/tui/zz_find_bench_test.go new file mode 100644 index 0000000..c6c5d00 --- /dev/null +++ b/tui/zz_find_bench_test.go @@ -0,0 +1,52 @@ +package tui + +import ( + "image/color" + "strings" + "testing" + + tea "charm.land/bubbletea/v2" +) + +func BenchmarkFindTmp(b *testing.B) { + m, dir := newTestModel(b) + var src strings.Builder + for i := range 20000 { + src.WriteString("\tx := compute(" + strings.Repeat("a", i%40) + ")\n") + } + write(b, dir, "big.go", "package a\nfunc f() {\n"+src.String()+"}\n") + m.reload() + m.pickFile(1) + m = step(b, m, tea.BackgroundColorMsg{Color: color.Black}) + keys := []tea.KeyPressMsg{{Code: '/', Text: "/"}} + for _, r := range "comput" { + keys = append(keys, tea.KeyPressMsg{Code: r, Text: string(r)}) + } + keys = append(keys, tea.KeyPressMsg{Code: tea.KeyEscape}) + for b.Loop() { + for _, k := range keys { + next, _ := m.Update(k) + m = *next.(*model) + _ = m.View() + } + } +} + +func BenchmarkPaintTmp(b *testing.B) { + m, dir := newTestModel(b) + var src strings.Builder + for range 200 { + src.WriteString("\tx := compute(a, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c)\n") + } + write(b, dir, "big.go", "package a\nfunc f() {\n"+src.String()+"}\n") + m.reload() + m.pickFile(1) + m = step(b, m, tea.BackgroundColorMsg{Color: color.Black}) + for _, s := range []string{"/", "c"} { + next, _ := m.Update(tea.KeyPressMsg{Code: rune(s[0]), Text: s}) + m = *next.(*model) + } + for b.Loop() { + _ = m.View() + } +} From 9b5062c9a7fb68903d8c9ea093f7ec18f68637bf Mon Sep 17 00:00:00 2001 From: Kenichiro Goto Date: Sun, 8 Nov 2026 21:01:06 +0900 Subject: [PATCH 11/11] tui: show a match that the file list cuts off MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A find in the file list matches the whole path, but a row cuts a long directory to "…/". A file that matched only in its directory then showed no paint, and n seemed to stop on files that did not match. The "…" of such a row is now painted, to show that the match is in the part that is cut off. --- tui/tui_test.go | 20 ++++++++++++++++++++ tui/view.go | 20 +++++++++++++++++++- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/tui/tui_test.go b/tui/tui_test.go index cb15fd7..c115741 100644 --- a/tui/tui_test.go +++ b/tui/tui_test.go @@ -1108,3 +1108,23 @@ func TestFindNarrow(t *testing.T) { t.Errorf("backspace to /re: %d hits, want %d", len(m.find.hits), all) } } + +// TestFindListCut checks that a file that matches by its directory shows +// that it matches, even when the list cuts the directory off. +func TestFindListCut(t *testing.T) { + m, dir := newTestModel(t) + if err := os.MkdirAll(filepath.Join(dir, "tui"), 0o755); err != nil { + t.Fatal(err) + } + write(t, dir, "tui/a_long_name_of_a_file.go", "package tui\n") + m.reload() + m = press(t, m, "tab", "/", "t", "u", "i", "enter") + lines := m.listLines(m.bodyHeight()) + i := slices.IndexFunc(lines, func(l string) bool { return strings.Contains(ansi.Strip(l), "…/a_long_name_of_a_file.go") }) + if i < 0 { + t.Fatalf("the list does not cut the directory:\n%s", view(m)) + } + if !strings.Contains(lines[i], findSGR+"…") { + t.Errorf("the row of a match does not paint its \"…\": %q", lines[i]) + } +} diff --git a/tui/view.go b/tui/view.go index 189504e..1bae208 100644 --- a/tui/view.go +++ b/tui/view.go @@ -222,7 +222,7 @@ func (m *model) listLines(h int) []string { for i := m.listStart(h); i < n && len(out) < h; i++ { r := row(i) if m.find.list && m.find.query != "" { - r = paintMatches(r, ansi.Strip(r), m.find.query) + r = m.paintListMatch(i, r) } if i == sel { r = m.selectedRow(r, w) @@ -232,6 +232,24 @@ func (m *model) listLines(h int) []string { return out } +// paintListMatch paints the matches of the find in row r of file i of the +// list. The find matches the whole path, but the row can cut off the +// directory. Then the "…" of a file that matches is painted, to show that +// the match is in the part that the row cuts off. +func (m *model) paintListMatch(i int, r string) string { + plain := ansi.Strip(r) + if painted := paintMatches(r, plain, m.find.query); painted != r { + return painted + } + _, hit := slices.BinarySearch(m.find.hits, i) + k := strings.Index(plain, "…") + if !hit || k < 0 { + return r + } + col := ansi.StringWidth(plain[:k]) + return paintSpans(r, [][2]int{{col, col + 1}}, findSGR) +} + // changeStat returns the counts of the lines that f adds and deletes, as // "+3 -1". It leaves out a count of 0, and marks a binary file. func changeStat(f changed) string {