diff --git a/README.md b/README.md index 3fb1940..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. @@ -65,7 +65,10 @@ 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 | +| `/` | 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 | @@ -110,6 +113,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/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..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"` @@ -104,9 +106,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"` @@ -162,6 +167,7 @@ func defaultConfig() config { MarkdownView: markdownViewSource, FileList: positionRight, FileListWidth: 32, + CursorLine: true, } } diff --git a/tui/find.go b/tui/find.go new file mode 100644 index 0000000..aea54a3 --- /dev/null +++ b/tui/find.go @@ -0,0 +1,292 @@ +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 + 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 + } + 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 { + for i := range n { + if match(i) { + f.hits = append(f.hits, i) + } + } + } + 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 +} + +// 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. +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) + 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 { + break + } + 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) +} + +// 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 + } + 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 b.String() +} diff --git a/tui/keys.go b/tui/keys.go index 7d9e807..7c3053d 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"), @@ -90,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"), @@ -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}, @@ -243,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"), @@ -275,7 +283,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..747461a 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 @@ -82,7 +84,13 @@ 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 + // 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 + 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 @@ -92,7 +100,8 @@ 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.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 @@ -120,8 +129,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) { @@ -154,11 +163,15 @@ 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 + 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. @@ -174,6 +187,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 { @@ -258,7 +278,9 @@ type model struct { mode mode overlay *overlay find findState + findBar textinput.Model drag dragState + click lastClick help help.Model status string @@ -308,6 +330,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) @@ -603,6 +627,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) } @@ -634,6 +660,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 0e9d7ec..cf672da 100644 --- a/tui/mouse.go +++ b/tui/mouse.go @@ -5,8 +5,12 @@ package tui // Click a file or a tab to open it. import ( + "time" + tea "charm.land/bubbletea/v2" "charm.land/lipgloss/v2" + + "github.com/frinfo702/rexdiff/diff" ) // onClick handles a press of a mouse button. @@ -21,6 +25,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() @@ -52,6 +59,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) @@ -65,10 +77,26 @@ 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 { + 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 d8dd8c3..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" @@ -16,8 +15,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. @@ -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): @@ -147,6 +151,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): @@ -217,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): @@ -233,6 +241,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) @@ -252,6 +261,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 == "" { @@ -360,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) @@ -456,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/render.go b/tui/render.go index 3d56469..ae356f1 100644 --- a/tui/render.go +++ b/tui/render.go @@ -89,27 +89,32 @@ 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 -// 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,8 @@ 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.src = &[2][]string{diff.Lines(f.Old), diff.Lines(f.New)} } p.addHeader(m.fileHeader(f)) } @@ -240,7 +246,8 @@ 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))) + p.src = &[2][]string{nil, diff.Lines(content)} } } diff --git a/tui/selection.go b/tui/selection.go index 1d0774b..09100e4 100644 --- a/tui/selection.go +++ b/tui/selection.go @@ -6,7 +6,11 @@ package tui // again and esc can clear it. import ( + "image/color" + "slices" + "strconv" "strings" + "unicode" "charm.land/bubbletea/v2" "charm.land/lipgloss/v2" @@ -49,6 +53,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. @@ -119,21 +156,16 @@ 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 paintSpans(line, [][2]int{{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 { +// 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. 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 var state byte for len(s) > 0 { seq, width, n, next := ansi.DecodeSequence(s, state, nil) @@ -142,14 +174,81 @@ func carrySGR(s, sgr string) string { break } b.WriteString(seq) - if width == 0 { - b.WriteString(sgr) + if width == 0 && strings.HasPrefix(seq, "\x1b[") && strings.HasSuffix(seq, "m") { + 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) + } } 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 +} + +// 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 3303fb0..b6d8939 100644 --- a/tui/selection_test.go +++ b/tui/selection_test.go @@ -2,6 +2,7 @@ package tui import ( "fmt" + "image/color" "strings" "testing" @@ -170,3 +171,35 @@ func TestMarkSelection(t *testing.T) { t.Errorf("marked line %q, want %q", got, want) } } + +// 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 + 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) + } + if setsBackground("38;2;48;0;0", false) { + 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/tui_test.go b/tui/tui_test.go index 520f3dc..c115741 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" @@ -87,6 +88,8 @@ func press(t *testing.T, m model, keys ...string) model { "esc": tea.KeyEscape, "home": tea.KeyHome, "end": tea.KeyEnd, + "tab": tea.KeyTab, + "bksp": tea.KeyBackspace, } for _, k := range keys { code, ok := named[k] @@ -222,8 +225,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() { @@ -233,6 +236,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) { @@ -962,3 +973,158 @@ 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) + } +} + +// 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") + } +} + +// 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") + } +} + +// 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") + } +} + +// 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) + } +} + +// 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") + } +} + +// 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) + } +} + +// 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 113145f..1bae208 100644 --- a/tui/view.go +++ b/tui/view.go @@ -2,6 +2,7 @@ package tui import ( "fmt" + "image/color" "path" "slices" "strings" @@ -220,6 +221,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 = m.paintListMatch(i, r) + } if i == sel { r = m.selectedRow(r, w) } @@ -228,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 { @@ -314,6 +336,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 +357,12 @@ 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) + } add(m.rowMark(i, t, lo, hi)+line, i) if t != nil && p.end(i) == i { addBelow(m.commentsBelow(t)) @@ -345,6 +374,33 @@ 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 "" + } + 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 { + return lipgloss.Darken(c, 0.06) + } + 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, 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, m.shade) + sgr + pad + ansi.ResetStyle +} + // emptyNote returns the text that shows instead of an empty pane, or "". func (m *model) emptyNote() string { p := m.cur() @@ -378,6 +434,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("▶ ") @@ -519,6 +576,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: 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() + } +}