Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,17 @@ while still being meaningful and self-contained.
excuse bundling it in. Before committing, review your diff and split out any
hunk that is behavior-preserving (an extraction, a rename, a move) into a
preceding commit, by staging hunks or resetting and recommitting in order.
- **A preparatory refactor is a new commit only when it prepares something
new.** Before adding one, find the commit that introduced the code you are
about to restructure. If that commit is on this branch, the refactor is a
`fixup!` for it rather than a commit of its own: a branch must never contain
a commit whose code a later commit on the same branch tidies up. A prep
refactor earns a commit of its own only when the shape it corrects came from
before the branch. This holds across a branch stack too — if the commit that
introduced the code is in an earlier branch of the stack, the fixup belongs
there, and the branches above it get replayed. The one exception is when
fixing it there turns out to be unreasonably difficult; ask me what to do
rather than deciding to leave the repair at the tip.
- **Do not use conventional commits** (no `feat:`/`fix:`/`chore:` prefixes).
Match the plain English imperative style of the existing history.
- **Wrap message body to 72 characters**. The subject is allowed to go up to 80
Expand Down
58 changes: 58 additions & 0 deletions pkg/gocui/search_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package gocui

import (
"fmt"
"testing"

"github.com/stretchr/testify/assert"
)

// writeLines writes the given lines to the view, as a task rendering content into it
// does: one line at a time.
func writeLines(v *View, lines ...string) {
for _, line := range lines {
fmt.Fprintf(v, "%s\n", line)
}
}

func TestSearchStatusAfterTheMatchesChange(t *testing.T) {
v := NewView("name", 0, 0, 40, 10, OutputNormal)
writeLines(v, "match", "other", "match", "other", "match")

v.Search("match", nil)
_ = v.gotoNextMatch()
_ = v.gotoNextMatch()
index, total := v.GetSearchStatus()
assert.Equal(t, 2, index)
assert.Equal(t, 3, total)

// The content is re-rendered with only the first of those matches left in it.
v.Clear()
writeLines(v, "match", "other", "other")

index, total = v.GetSearchStatus()
assert.Equal(t, 0, index)
assert.Equal(t, 1, total)
}

func TestSearchPositionsFollowStreamedContent(t *testing.T) {
v := NewView("name", 0, 0, 40, 10, OutputNormal)
v.Search("match", nil)

// A render arrives a line at a time, and the status describes all of it.
writeLines(v, "other", "match", "other", "match")

_, total := v.GetSearchStatus()
assert.Equal(t, 2, total)
}

func BenchmarkWriteToSearchedView(b *testing.B) {
for b.Loop() {
v := NewView("name", 0, 0, 100, 40, OutputNormal)
v.Search("match", nil)
for i := range 2000 {
fmt.Fprintf(v, "line %d of a diff, most of which does not match\n", i)
}
v.GetSearchStatus()
}
}
61 changes: 60 additions & 1 deletion pkg/gocui/view.go
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,12 @@ type searcher struct {
currentSearchIndex int
onSelectItem func(*View, int)
renderSearchStatus func(*View, int, int)

// Whether the content has changed since the positions were worked out, so that
// they have to be worked out again before they are read. Working them out walks
// the whole view, and content arrives a line at a time, so it happens once per
// read rather than once per line written.
positionsStale bool
}

func (v *View) setRenderSearchStatus(renderSearchStatus func(*View, int, int)) {
Expand All @@ -287,7 +293,40 @@ func (v *View) renderSearchStatus(index int, itemCount int) {
}
}

// refreshSearchPositions works the search positions out again if the content has
// changed since they were last worked out. Every read of the positions goes through
// this, so that no caller has to know whether the view has been drawn since the
// content it is asking about arrived.
func (v *View) refreshSearchPositions() {
v.writeMutex.Lock()
defer v.writeMutex.Unlock()

v.refreshSearchPositionsIfNeeded()
}

// refreshSearchPositions for a caller that already holds writeMutex.
func (v *View) refreshSearchPositionsIfNeeded() {
if v.searcher.positionsStale {
v.updateSearchPositions()
}
}

// RefreshSearch runs the search again over content the view has just been re-rendered
// with, and shows the "x of y" status of what it finds. The view stays where it is: the
// position in the content is the user's, and the search follows it rather than moving
// it.
func (v *View) RefreshSearch() {
if !v.IsSearching() {
return
}

v.UpdateSearchResults(v.searcher.searchString, v.searcher.modelSearchResults)
v.renderSearchStatus(v.searcher.currentSearchIndex, len(v.searcher.searchPositions))
}

func (v *View) gotoNextMatch() error {
v.refreshSearchPositions()

if len(v.searcher.searchPositions) == 0 {
return nil
}
Expand All @@ -307,6 +346,8 @@ func (v *View) gotoNextMatch() error {
}

func (v *View) gotoPreviousMatch() error {
v.refreshSearchPositions()

if len(v.searcher.searchPositions) == 0 {
return nil
}
Expand All @@ -328,6 +369,8 @@ func (v *View) gotoPreviousMatch() error {
}

func (v *View) SelectSearchResult(index int) {
v.refreshSearchPositions()

itemCount := len(v.searcher.searchPositions)
if itemCount == 0 {
return
Expand All @@ -347,6 +390,8 @@ func (v *View) SelectSearchResult(index int) {

// Returns <current match index>, <total matches>
func (v *View) GetSearchStatus() (int, int) {
v.refreshSearchPositions()

return v.searcher.currentSearchIndex, len(v.searcher.searchPositions)
}

Expand Down Expand Up @@ -420,6 +465,8 @@ func (v *View) nearestSearchPosition() int {
}

func (v *View) SetNearestSearchPosition() {
v.refreshSearchPositions()

if len(v.searcher.searchPositions) > 0 {
newPos := v.nearestSearchPosition()
if newPos != v.searcher.currentSearchIndex {
Expand Down Expand Up @@ -902,7 +949,7 @@ func (v *View) write(p []byte) {

v.buf.write(v, p)

v.updateSearchPositions()
v.searcher.positionsStale = true
}

// write parses p into cells and appends them to the buffer at its write cursor.
Expand Down Expand Up @@ -1353,6 +1400,8 @@ func stringToGraphemes(s string) []string {
}

func (v *View) updateSearchPositions() {
v.searcher.positionsStale = false

if v.searcher.searchString != "" {
var normalizeRune func(s string) string
var normalizedSearchStr string
Expand Down Expand Up @@ -1431,6 +1480,11 @@ func (v *View) updateSearchPositions() {
}
}
}

// The content may hold fewer matches than it did, so the current one is brought
// back into range: readers index the positions by it.
v.searcher.currentSearchIndex = min(v.searcher.currentSearchIndex,
max(0, len(v.searcher.searchPositions)-1))
}

// IsTainted tells us if the view is tainted
Expand Down Expand Up @@ -1461,6 +1515,7 @@ func (v *View) draw(isWindowFocused bool) {
}

v.refreshViewLinesIfNeeded()
v.refreshSearchPositionsIfNeeded()

visibleViewLinesHeight := v.viewLineLengthIgnoringTrailingBlankLines()
if v.Autoscroll && visibleViewLinesHeight > maxY {
Expand Down Expand Up @@ -2070,6 +2125,8 @@ func (v *View) setContentLineCount(lineCount int) {
// result that is visible in the view, if any, or the first one that is below the view if none is
// visible.
func (v *View) selectVisibleSearchResultAfterScrollUp() {
v.refreshSearchPositions()

if !v.Highlight && len(v.searcher.searchPositions) != 0 {
windowBottom := v.oy + v.InnerHeight()
if v.searcher.searchPositions[v.searcher.currentSearchIndex].Y >= windowBottom {
Expand All @@ -2093,6 +2150,8 @@ func (v *View) selectVisibleSearchResultAfterScrollUp() {
// result that is visible in the view, if any, or the last one that is above the view if none is
// visible.
func (v *View) selectVisibleSearchResultAfterScrollDown() {
v.refreshSearchPositions()

if !v.Highlight && len(v.searcher.searchPositions) != 0 {
if v.searcher.searchPositions[v.searcher.currentSearchIndex].Y < v.oy {
newSearchIndex := v.searcher.currentSearchIndex
Expand Down
15 changes: 15 additions & 0 deletions pkg/gui/main_panels.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package gui

import (
"github.com/jesseduffield/lazygit/pkg/gocui"
"github.com/jesseduffield/lazygit/pkg/gui/context"
"github.com/jesseduffield/lazygit/pkg/gui/types"
)

Expand Down Expand Up @@ -139,3 +140,17 @@ func (gui *Gui) refreshMainViews(opts types.RefreshMainOpts) {
func (gui *Gui) splitMainPanel(splitMainPanel bool) {
gui.State.SplitMainPanel = splitMainPanel
}

// reApplySearch runs a search the view holds again over the content a render has just
// finished putting there, so that the matches highlighted and the "x of y" status
// describe what the view shows now rather than what it showed when the search was
// typed. Call it once the content is final.
func (gui *Gui) reApplySearch(view *gocui.View) {
// While the prompt is open, the search view holds what the user is typing, and the
// status would be written over it.
if gui.State.ContextMgr.Current().GetKey() == context.SEARCH_CONTEXT_KEY {
return
}

view.RefreshSearch()
}
5 changes: 5 additions & 0 deletions pkg/gui/tasks_adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ func (gui *Gui) newStringTaskWithoutScroll(view *gocui.View, str string) error {
f := func(tasks.TaskOpts) error {
return gui.g.OnUIThreadAndWaitBackground(func() {
gui.c.SetViewContent(view, str)
gui.reApplySearch(view)
})
}

Expand All @@ -108,6 +109,7 @@ func (gui *Gui) newStringTaskWithScroll(view *gocui.View, str string, originX in
return gui.g.OnUIThreadAndWaitBackground(func() {
gui.c.SetViewContent(view, str)
view.SetOrigin(originX, originY)
gui.reApplySearch(view)
})
}

Expand All @@ -125,6 +127,7 @@ func (gui *Gui) newStringTaskWithKey(view *gocui.View, str string, key string) e
return gui.g.OnUIThreadAndWaitBackground(func() {
gui.c.ResetViewOrigin(view)
gui.c.SetViewContent(view, str)
gui.reApplySearch(view)
})
}

Expand Down Expand Up @@ -170,6 +173,8 @@ func (gui *Gui) getManager(view *gocui.View) *tasks.ViewBufferManager {

view.SetOrigin(0, newOriginY)
}

gui.reApplySearch(view)
},
func() {
view.SetOrigin(0, 0)
Expand Down
24 changes: 15 additions & 9 deletions pkg/gui/view_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,18 @@ func (gui *Gui) linesToReadFromCmdTask(v *gocui.View) tasks.LinesToRead {

linesForFirstRefresh := height + oy + 10

// A search counts the matches in everything the view holds, so a re-render of a
// view that is being searched is read all the way to the end (as opening the
// search prompt reads it, see MainViewController.openSearch). Lines left unread
// hold matches the search doesn't know about, and would add themselves to the
// "x of y" as the user scrolled far enough to load them.
if v.IsSearching() {
return tasks.LinesToRead{
Total: -1,
InitialRefreshAfter: linesForFirstRefresh,
}
}

// We want to read as many lines initially as necessary to let the
// scrollbar go to its minimum height, so that the scrollbar thumb doesn't
// change size as you scroll down.
Expand Down Expand Up @@ -159,15 +171,9 @@ func (gui *Gui) postRefreshUpdate(c types.Context, opts types.OnFocusOpts) {

currentCtx := gui.State.ContextMgr.Current()
if currentCtx.GetKey() == context.NORMAL_MAIN_CONTEXT_KEY || currentCtx.GetKey() == context.NORMAL_SECONDARY_CONTEXT_KEY {
// Searching can't cope well with the view being updated while it is being searched.
// We might be able to fix the problems with this, but it doesn't seem easy, so for now
// just don't rerender the view while searching, on the assumption that users will probably
// either search or change their data, but not both at the same time.
if !currentCtx.GetView().IsSearching() {
sidePanelContext := gui.State.ContextMgr.NextInStack(currentCtx)
if sidePanelContext != nil && sidePanelContext.GetKey() == c.GetKey() {
sidePanelContext.HandleRenderToMain()
}
sidePanelContext := gui.State.ContextMgr.NextInStack(currentCtx)
if sidePanelContext != nil && sidePanelContext.GetKey() == c.GetKey() {
sidePanelContext.HandleRenderToMain()
}
} else if c.GetKey() == gui.State.ContextMgr.CurrentStatic().GetKey() {
// If our view is not the current one, but it is the current static context, then this
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package filter_and_search

import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)

var RerenderTheSearchedMainView = NewIntegrationTest(NewIntegrationTestArgs{
Description: "A refresh renders the focused main view again even while it is being searched",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(config *config.AppConfig) {},
SetupRepo: func(shell *Shell) {
shell.CreateFileAndAdd("file1", "one\ntwo\nthree\n")
shell.Commit("one")

shell.UpdateFile("file1", "one\nNEEDLE\nthree\n")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Files().
IsFocused().
Press(keys.Universal.FocusMainView)

t.Views().Main().
IsFocused().
FilterOrSearch("NEEDLE").
Content(Contains("+NEEDLE")).
Tap(func() {
t.Shell().UpdateFile("file1", "one\nOTHER\nthree\n")
}).
Press(keys.Universal.Refresh).
Content(Contains("+OTHER")).
Content(DoesNotContain("+NEEDLE"))

t.Views().Search().Content(Contains("No matches for 'NEEDLE'"))
},
})
Loading
Loading