From 70e87d9f270736074aa6079de509a1077aff336a Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Sun, 16 Aug 2026 14:00:47 +0200 Subject: [PATCH 01/21] Leave a command with nothing to say out of the options bar MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A command that acts on a diff selection has nothing to say over content that isn't a diff, and says so by describing itself as nothing — but a binding that is displayed on screen is displayed whatever its description, so it would show as a key with an empty label. Leave it out instead. Co-authored-by: Claude Opus 5 (1M context) --- pkg/gui/options_map.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/pkg/gui/options_map.go b/pkg/gui/options_map.go index 962187bff..880a766b8 100644 --- a/pkg/gui/options_map.go +++ b/pkg/gui/options_map.go @@ -50,7 +50,11 @@ func (self *OptionsMapMgr) renderContextOptionsMap() { })...) bindingsToDisplay := lo.Filter(allBindings, func(binding *types.Binding, _ int) bool { - return len(binding.Keys) > 0 && binding.DisplayOnScreen && !binding.IsDisabled() + // A binding that describes itself as nothing has nothing to do where we are — + // that is how a command which only applies to some of a view's contents says so + // — and an empty entry in the options bar would say nothing about it. + return len(binding.Keys) > 0 && binding.DisplayOnScreen && !binding.IsDisabled() && + binding.GetShortDescription() != "" }) optionsMap := lo.Map(bindingsToDisplay, func(binding *types.Binding, _ int) bindingInfo { From 1169cde15714145ad68996f6bd8b91e87dbd3a4a Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Sun, 16 Aug 2026 06:37:09 +0200 Subject: [PATCH 02/21] Stage and unstage diff lines from the focused main view MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Space in the focused main view now acts on the selected lines the way it does in the staging view: over the working tree's unstaged changes it puts them into the index, and over the staged ones it takes them back out. Which of the two it does is a property of the pane, each side of the diff having one of its own. Nothing has to be entered first, and a selection reaching across several files of a directory's diff is applied as one patch per file. The rows on screen are only a picture of the diff, so the patch is built from the diff itself: each selected row's identity — which file, which line of it, and whether it is a deletion — is looked for in the file's own diff, and the lines that match are the ones the patch includes. Matching by position rather than by counting rows is what tells the two halves of a modified line apart, since the deletion and the addition replacing it sit at the same place in the new file. Panels other than the working tree offer no action on their diff yet, so space says nothing and does nothing there. Co-authored-by: Claude Opus 5 (1M context) --- docs-master/keybindings/Keybindings_en.md | 2 + docs-master/keybindings/Keybindings_ja.md | 2 + docs-master/keybindings/Keybindings_ko.md | 2 + docs-master/keybindings/Keybindings_nl.md | 2 + docs-master/keybindings/Keybindings_pl.md | 2 + docs-master/keybindings/Keybindings_pt.md | 2 + docs-master/keybindings/Keybindings_ru.md | 2 + docs-master/keybindings/Keybindings_zh-CN.md | 2 + docs-master/keybindings/Keybindings_zh-TW.md | 2 + .../controllers/helpers/diff_line_queries.go | 9 ++ pkg/gui/controllers/main_view_controller.go | 42 +++++ .../controllers/working_tree_diff_actions.go | 144 +++++++++++++++++- pkg/gui/types/context.go | 18 +++ .../no_selection_over_a_binary_diff.go | 22 ++- .../tests/main_view/stage_diff_lines.go | 70 +++++++++ ...stage_diff_lines_of_a_path_with_a_space.go | 52 +++++++ .../main_view/stage_range_spanning_files.go | 55 +++++++ .../tests/main_view/unstage_diff_lines.go | 57 +++++++ pkg/integration/tests/test_list.go | 4 + 19 files changed, 489 insertions(+), 2 deletions(-) create mode 100644 pkg/integration/tests/main_view/stage_diff_lines.go create mode 100644 pkg/integration/tests/main_view/stage_diff_lines_of_a_path_with_a_space.go create mode 100644 pkg/integration/tests/main_view/stage_range_spanning_files.go create mode 100644 pkg/integration/tests/main_view/unstage_diff_lines.go diff --git a/docs-master/keybindings/Keybindings_en.md b/docs-master/keybindings/Keybindings_en.md index 6f3d6cbac..749cdd9e8 100644 --- a/docs-master/keybindings/Keybindings_en.md +++ b/docs-master/keybindings/Keybindings_en.md @@ -226,6 +226,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` a `` | Toggle hunk selection | Toggle line-by-line vs. hunk selection mode. | | `` v `` | Toggle range select | | | `` e `` | Edit file | Open file in external editor. | +| `` `` | Stage | Toggle selection staged / unstaged. | | `` `` | Copy selected text to clipboard | | | `` , h `` | Go to previous hunk | | | `` , l `` | Go to next hunk | | @@ -339,6 +340,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` a `` | Toggle hunk selection | Toggle line-by-line vs. hunk selection mode. | | `` v `` | Toggle range select | | | `` e `` | Edit file | Open file in external editor. | +| `` `` | Stage | Toggle selection staged / unstaged. | | `` `` | Copy selected text to clipboard | | | `` , h `` | Go to previous hunk | | | `` , l `` | Go to next hunk | | diff --git a/docs-master/keybindings/Keybindings_ja.md b/docs-master/keybindings/Keybindings_ja.md index 7fd62f726..331becbd0 100644 --- a/docs-master/keybindings/Keybindings_ja.md +++ b/docs-master/keybindings/Keybindings_ja.md @@ -195,6 +195,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` a `` | ハンクの選択を切り替える | Toggle line-by-line vs. hunk selection mode. | | `` v `` | 範囲選択を切り替え | | | `` e `` | ファイルを編集 | 外部エディタでファイルを開きます。 | +| `` `` | ステージ | 選択された部分のステージ / アンステージを切り替えます。 | | `` `` | 選択したテキストをクリップボードにコピー | | | `` , h `` | 前のハンクに移動 | | | `` , l `` | 次のハンクに移動 | | @@ -316,6 +317,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` a `` | ハンクの選択を切り替える | Toggle line-by-line vs. hunk selection mode. | | `` v `` | 範囲選択を切り替え | | | `` e `` | ファイルを編集 | 外部エディタでファイルを開きます。 | +| `` `` | ステージ | 選択された部分のステージ / アンステージを切り替えます。 | | `` `` | 選択したテキストをクリップボードにコピー | | | `` , h `` | 前のハンクに移動 | | | `` , l `` | 次のハンクに移動 | | diff --git a/docs-master/keybindings/Keybindings_ko.md b/docs-master/keybindings/Keybindings_ko.md index b0437591f..adf015638 100644 --- a/docs-master/keybindings/Keybindings_ko.md +++ b/docs-master/keybindings/Keybindings_ko.md @@ -87,6 +87,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` a `` | Toggle hunk selection | Toggle line-by-line vs. hunk selection mode. | | `` v `` | 드래그 선택 전환 | | | `` e `` | 파일 편집 | Open file in external editor. | +| `` `` | Staged 전환 | 선택한 행을 staged / unstaged | | `` `` | 선택한 텍스트를 클립보드에 복사 | | | `` , h `` | 이전 hunk를 선택 | | | `` , l `` | 다음 hunk를 선택 | | @@ -173,6 +174,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` a `` | Toggle hunk selection | Toggle line-by-line vs. hunk selection mode. | | `` v `` | 드래그 선택 전환 | | | `` e `` | 파일 편집 | Open file in external editor. | +| `` `` | Staged 전환 | 선택한 행을 staged / unstaged | | `` `` | 선택한 텍스트를 클립보드에 복사 | | | `` , h `` | 이전 hunk를 선택 | | | `` , l `` | 다음 hunk를 선택 | | diff --git a/docs-master/keybindings/Keybindings_nl.md b/docs-master/keybindings/Keybindings_nl.md index 3d7012267..e2db96275 100644 --- a/docs-master/keybindings/Keybindings_nl.md +++ b/docs-master/keybindings/Keybindings_nl.md @@ -234,6 +234,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` a `` | Wissel tussen hunk selectie aan of uit | Wissel tussen regel-voor-regel of hunk selectie modus. | | `` v `` | Toggle drag selecteer | | | `` e `` | Verander bestand | Open bestand in externe editor. | +| `` `` | Toggle staged | Toggle lijnen staged / unstaged | | `` `` | Copy selected text to clipboard | | | `` , h `` | Selecteer de vorige hunk | | | `` , l `` | Selecteer de volgende hunk | | @@ -317,6 +318,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` a `` | Wissel tussen hunk selectie aan of uit | Wissel tussen regel-voor-regel of hunk selectie modus. | | `` v `` | Toggle drag selecteer | | | `` e `` | Verander bestand | Open bestand in externe editor. | +| `` `` | Toggle staged | Toggle lijnen staged / unstaged | | `` `` | Copy selected text to clipboard | | | `` , h `` | Selecteer de vorige hunk | | | `` , l `` | Selecteer de volgende hunk | | diff --git a/docs-master/keybindings/Keybindings_pl.md b/docs-master/keybindings/Keybindings_pl.md index e79338b3c..0b1f4c763 100644 --- a/docs-master/keybindings/Keybindings_pl.md +++ b/docs-master/keybindings/Keybindings_pl.md @@ -102,6 +102,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` a `` | Toggle hunk selection | Toggle line-by-line vs. hunk selection mode. | | `` v `` | Przełącz zaznaczenie zakresu | | | `` e `` | Edytuj plik | Otwórz plik w zewnętrznym edytorze. | +| `` `` | Zatwierdź | Przełącz zaznaczenie zatwierdzone/niezatwierdzone. | | `` `` | Kopiuj zaznaczony tekst do schowka | | | `` , h `` | Idź do poprzedniego fragmentu | | | `` , l `` | Idź do następnego fragmentu | | @@ -212,6 +213,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` a `` | Toggle hunk selection | Toggle line-by-line vs. hunk selection mode. | | `` v `` | Przełącz zaznaczenie zakresu | | | `` e `` | Edytuj plik | Otwórz plik w zewnętrznym edytorze. | +| `` `` | Zatwierdź | Przełącz zaznaczenie zatwierdzone/niezatwierdzone. | | `` `` | Kopiuj zaznaczony tekst do schowka | | | `` , h `` | Idź do poprzedniego fragmentu | | | `` , l `` | Idź do następnego fragmentu | | diff --git a/docs-master/keybindings/Keybindings_pt.md b/docs-master/keybindings/Keybindings_pt.md index 4041c5edd..8f8d2814b 100644 --- a/docs-master/keybindings/Keybindings_pt.md +++ b/docs-master/keybindings/Keybindings_pt.md @@ -238,6 +238,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` a `` | Toggle hunk selection | Ativa/desativa modo linha por linha vs. modo de seleção por partes. | | `` v `` | Toggle range select | | | `` e `` | Editar arquivo | Abrir arquivo no editor externo. | +| `` `` | Etapa | Ativar/desativar seleção em staged/unstaged | | `` `` | Copiar texto selecionado para área de transferência | | | `` , h `` | Ir para o local anterior | | | `` , l `` | Ir para o próximo trecho | | @@ -348,6 +349,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` a `` | Toggle hunk selection | Ativa/desativa modo linha por linha vs. modo de seleção por partes. | | `` v `` | Toggle range select | | | `` e `` | Editar arquivo | Abrir arquivo no editor externo. | +| `` `` | Etapa | Ativar/desativar seleção em staged/unstaged | | `` `` | Copiar texto selecionado para área de transferência | | | `` , h `` | Ir para o local anterior | | | `` , l `` | Ir para o próximo trecho | | diff --git a/docs-master/keybindings/Keybindings_ru.md b/docs-master/keybindings/Keybindings_ru.md index d113eb4fa..399e86305 100644 --- a/docs-master/keybindings/Keybindings_ru.md +++ b/docs-master/keybindings/Keybindings_ru.md @@ -77,6 +77,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` a `` | Toggle hunk selection | Toggle line-by-line vs. hunk selection mode. | | `` v `` | Переключить выборку перетаскивания | | | `` e `` | Редактировать файл | Open file in external editor. | +| `` `` | Переключить индекс | Переключить строку в проиндексированные / непроиндексированные | | `` `` | Скопировать выделенный текст в буфер обмена | | | `` , h `` | Выбрать предыдущую часть | | | `` , l `` | Выбрать следующую часть | | @@ -117,6 +118,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` a `` | Toggle hunk selection | Toggle line-by-line vs. hunk selection mode. | | `` v `` | Переключить выборку перетаскивания | | | `` e `` | Редактировать файл | Open file in external editor. | +| `` `` | Переключить индекс | Переключить строку в проиндексированные / непроиндексированные | | `` `` | Скопировать выделенный текст в буфер обмена | | | `` , h `` | Выбрать предыдущую часть | | | `` , l `` | Выбрать следующую часть | | diff --git a/docs-master/keybindings/Keybindings_zh-CN.md b/docs-master/keybindings/Keybindings_zh-CN.md index 97d006713..9e12bc5d2 100644 --- a/docs-master/keybindings/Keybindings_zh-CN.md +++ b/docs-master/keybindings/Keybindings_zh-CN.md @@ -289,6 +289,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` a `` | 切换代码块选择 | 切换逐行选择与代码块选择模式。 | | `` v `` | 切换拖动选择 | | | `` e `` | 编辑文件 | 使用外部编辑器打开文件 | +| `` `` | 切换暂存状态 | 切换行暂存状态 | | `` `` | 复制选中文本到剪贴板 | | | `` , h `` | 选择上一个区块 | | | `` , l `` | 选择下一个区块 | | @@ -345,6 +346,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` a `` | 切换代码块选择 | 切换逐行选择与代码块选择模式。 | | `` v `` | 切换拖动选择 | | | `` e `` | 编辑文件 | 使用外部编辑器打开文件 | +| `` `` | 切换暂存状态 | 切换行暂存状态 | | `` `` | 复制选中文本到剪贴板 | | | `` , h `` | 选择上一个区块 | | | `` , l `` | 选择下一个区块 | | diff --git a/docs-master/keybindings/Keybindings_zh-TW.md b/docs-master/keybindings/Keybindings_zh-TW.md index cc8116843..2adf9ac93 100644 --- a/docs-master/keybindings/Keybindings_zh-TW.md +++ b/docs-master/keybindings/Keybindings_zh-TW.md @@ -78,6 +78,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` a `` | 切換程式碼塊選擇 | 切換逐行選擇與程式碼塊選擇模式。 | | `` v `` | 切換拖曳選擇 | | | `` e `` | 編輯檔案 | 使用外部編輯器開啟 | +| `` `` | 切換預存 | 切換現有行的狀態 (已預存/未預存) | | `` `` | 複製所選文本至剪貼簿 | | | `` , h `` | 選擇上一段 | | | `` , l `` | 選擇下一段 | | @@ -367,6 +368,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` a `` | 切換程式碼塊選擇 | 切換逐行選擇與程式碼塊選擇模式。 | | `` v `` | 切換拖曳選擇 | | | `` e `` | 編輯檔案 | 使用外部編輯器開啟 | +| `` `` | 切換預存 | 切換現有行的狀態 (已預存/未預存) | | `` `` | 複製所選文本至剪貼簿 | | | `` , h `` | 選擇上一段 | | | `` , l `` | 選擇下一段 | | diff --git a/pkg/gui/controllers/helpers/diff_line_queries.go b/pkg/gui/controllers/helpers/diff_line_queries.go index 77f82953b..1f623b937 100644 --- a/pkg/gui/controllers/helpers/diff_line_queries.go +++ b/pkg/gui/controllers/helpers/diff_line_queries.go @@ -34,6 +34,15 @@ func (self *DiffLineHelper) DiffLinesInBufferRange(view *gocui.View, first int, return infos } +// ChangeLinesInBufferRange returns the change lines — the additions and deletions — +// among the diff lines shown by the rows in the inclusive buffer-line range. Those are +// the lines a patch is built from: a patch carries whatever context it needs around +// them by itself, so a selection contributes only its changes. +func (self *DiffLineHelper) ChangeLinesInBufferRange(view *gocui.View, first int, last int) []types.DiffLineInfo { + return lo.Filter(self.DiffLinesInBufferRange(view, first, last), + func(info types.DiffLineInfo, _ int) bool { return info.IsChange() }) +} + // changeLines resolves view's rendered diff to one flag per buffer line: whether // that row is a change line (an addition or a deletion), as opposed to context, a // header, or a row whose identity couldn't be recovered. Those are the rows a diff --git a/pkg/gui/controllers/main_view_controller.go b/pkg/gui/controllers/main_view_controller.go index a504596b5..b814ea0fa 100644 --- a/pkg/gui/controllers/main_view_controller.go +++ b/pkg/gui/controllers/main_view_controller.go @@ -79,6 +79,15 @@ func (self *MainViewController) GetKeybindings(opts types.KeybindingsOpts) []*ty GetDisabledReason: self.diffSelectionDisabledReason, Tooltip: self.c.Tr.EditFileTooltip, }, + { + Keys: opts.GetKeys(opts.Config.Universal.Select), + Handler: self.primaryAction, + Description: self.c.Tr.Stage, + DescriptionFunc: self.workingTreeActionDescription(self.c.Tr.Stage), + GetDisabledReason: self.diffSelectionDisabledReason, + Tooltip: self.c.Tr.StageSelectionTooltip, + DisplayOnScreen: true, + }, { Keys: opts.GetKeys(opts.Config.Universal.CopyToClipboard), Handler: self.copySelection, @@ -269,6 +278,39 @@ func (self *MainViewController) diffSource() types.FocusedMainViewDiffSource { return sidePanel.GetFocusedMainViewDiffSource() } +// focusedMainViewActions returns what the panel beneath the focused main view does to +// a selection in its diff, or nil where it does nothing to it — a panel whose diff can +// be read and copied but not acted on. +func (self *MainViewController) focusedMainViewActions() types.FocusedMainViewActions { + actions, _ := self.diffSource().(types.FocusedMainViewActions) + return actions +} + +// primaryAction acts on the selected diff lines, leaving what that means to the panel +// beneath — which also re-renders the diff, since it is the one that changed it. +func (self *MainViewController) primaryAction() error { + actions := self.focusedMainViewActions() + if actions == nil { + return nil + } + first, last, ok := self.context.GetView().SelectedBufferLineRange() + if !ok { + return nil + } + return actions.PrimaryAction(self.context, first, last) +} + +// workingTreeActionDescription gives a command's description only where the command +// applies — over the working tree's diff — so that it is listed there and nowhere else. +func (self *MainViewController) workingTreeActionDescription(description string) func() string { + return func() string { + if self.diffMainViewType() != types.DiffMainViewTypeStaging { + return "" + } + return description + } +} + // copySelection copies the selected diff lines to the clipboard — not as the diff // renderer drew them, but as they read in the diff itself, which is both what you meant // to copy and the only form a renderer can't have mangled. A selection that is all diff --git a/pkg/gui/controllers/working_tree_diff_actions.go b/pkg/gui/controllers/working_tree_diff_actions.go index 889cc0859..e75d538f2 100644 --- a/pkg/gui/controllers/working_tree_diff_actions.go +++ b/pkg/gui/controllers/working_tree_diff_actions.go @@ -1,8 +1,16 @@ package controllers import ( + "fmt" + "path/filepath" + + "github.com/jesseduffield/generics/set" + "github.com/jesseduffield/lazygit/pkg/commands/git_commands" + "github.com/jesseduffield/lazygit/pkg/commands/models" + "github.com/jesseduffield/lazygit/pkg/commands/patch" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/types" + "github.com/samber/lo" ) // WorkingTreeDiffActions implements what the files panel offers on the diff it renders @@ -12,7 +20,7 @@ type WorkingTreeDiffActions struct { c *ControllerCommon } -var _ types.FocusedMainViewDiffSource = &WorkingTreeDiffActions{} +var _ types.FocusedMainViewActions = &WorkingTreeDiffActions{} func NewWorkingTreeDiffActions(c *ControllerCommon) *WorkingTreeDiffActions { return &WorkingTreeDiffActions{c: c} @@ -42,3 +50,137 @@ func (self *WorkingTreeDiffActions) PlainDiff(pane types.DiffPaneContext, paths func (self *WorkingTreeDiffActions) showsStagedSide(pane types.DiffPaneContext) bool { return pane.GetKey() == self.c.Contexts().NormalSecondary.GetKey() } + +// PrimaryAction stages the selected diff lines, or takes them back out of the index +// when what is selected is the staged side of the diff. +func (self *WorkingTreeDiffActions) PrimaryAction(pane types.DiffPaneContext, firstBufferLine int, lastBufferLine int) error { + if self.c.UserConfig().Git.DiffContextSize == 0 { + return fmt.Errorf(self.c.Tr.Actions.NotEnoughContextToStage, + self.c.UserConfig().Keybinding.Universal.IncreaseContextInDiffView) + } + + infos, onStagedSide, ok := self.diffLineSelection(pane, firstBufferLine, lastBufferLine) + if !ok { + return nil + } + + // Either way the patch goes to the index: forwards from the unstaged side to stage + // it, backwards from the staged side to take it back out. + return self.applyDiffLineSelection(infos, onStagedSide, + git_commands.ApplyPatchOpts{Reverse: onStagedSide, Cached: true}) +} + +// diffLineSelection resolves what the user has selected in a pane of the focused main +// view to the change lines to act on, and reports whether they are the staged side of +// the diff — which is a question about the pane, so it is the same for every file of a +// directory's diff. ok is false when the selection holds no change line, in which case +// there is nothing to act on. +func (self *WorkingTreeDiffActions) diffLineSelection( + pane types.DiffPaneContext, firstBufferLine int, lastBufferLine int, +) (infos []types.DiffLineInfo, onStagedSide bool, ok bool) { + infos = self.c.Helpers().DiffLine.ChangeLinesInBufferRange(pane.GetView(), firstBufferLine, lastBufferLine) + if len(infos) == 0 { + return nil, false, false + } + return infos, self.showsStagedSide(pane), true +} + +// applyDiffLineSelection applies the selected change lines, a patch per file, and +// re-renders what that changed. onStagedSide says which of the file's two diffs the +// lines were selected in and so are to be found in; opts says how to apply them. +func (self *WorkingTreeDiffActions) applyDiffLineSelection( + infos []types.DiffLineInfo, onStagedSide bool, opts git_commands.ApplyPatchOpts, +) error { + self.c.LogAction(self.c.Tr.Actions.ApplyPatch) + + // A directory's diff spans several files, and a patch is of one file, so the + // selected lines are grouped by the file they belong to and applied file by file. + infosByFile := lo.GroupBy(infos, func(info types.DiffLineInfo) string { return info.Path }) + for path, fileInfos := range infosByFile { + file := self.fileForDiffLinePath(path) + if file == nil { + continue + } + if err := self.applyDiffLines(file, fileInfos, onStagedSide, opts); err != nil { + return err + } + } + + // Block input until the refresh has landed, so that a quick second keypress acts on + // the diff as it now is rather than on the one we just changed. + self.c.RefreshBlockingInput(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}}) + return nil +} + +// fileForDiffLinePath maps the absolute path a diff line carries to the working tree +// file it belongs to, or nil for a path that is no file of this repo's working tree. +func (self *WorkingTreeDiffActions) fileForDiffLinePath(path string) *models.File { + relativePath, err := filepath.Rel(self.c.Git().RepoPaths.WorktreePath(), path) + if err != nil { + return nil + } + return self.context().FileTreeViewModel.GetFile(filepath.ToSlash(relativePath)) +} + +// applyDiffLines applies the given change lines of one file — a line, a hunk, a range — +// as a patch built from that file's own diff: +// +// - stage: read the unstaged diff, apply it to the index +// - unstage: read the staged diff, apply it to the index backwards +// +// sourceCached names the diff the lines were selected in, which is where they are found +// again; opts says how to apply what is built from them. The two are independent — a +// discard reads one side and reverses it — so they are passed separately. +// +// Each selected line is looked for by where it sits in the file. This tells the two +// halves of a modified line apart: the deletion and the addition replacing it share a +// position in the new file and differ only in being a deletion. Context lines are not +// selected: a patch of the lines you picked keeps whatever context it needs around +// them by itself. +func (self *WorkingTreeDiffActions) applyDiffLines( + file *models.File, infos []types.DiffLineInfo, sourceCached bool, opts git_commands.ApplyPatchOpts, +) error { + parsedPatch := patch.Parse(self.c.Git().WorkingTree.WorktreeFileDiff(file, true, sourceCached)) + + type changeLine struct { + lineNumber int + isDeletion bool + } + selected := set.New[changeLine]() + for _, info := range infos { + if info.Type == types.DiffLineDeleted { + selected.Add(changeLine{info.OldLine, true}) + } else { + selected.Add(changeLine{info.NewLine, false}) + } + } + + var patchLineIndices []int + for idx, line := range parsedPatch.Lines() { + var key changeLine + switch { + case line.IsAddition(): + key = changeLine{parsedPatch.LineNumberOfLine(idx), false} + case line.IsDeletion(): + key = changeLine{parsedPatch.OldLineNumberOfLine(idx), true} + default: + continue + } + if selected.Includes(key) { + patchLineIndices = append(patchLineIndices, idx) + } + } + + patchToApply := parsedPatch. + Transform(patch.TransformOpts{ + Reverse: opts.Reverse, + IncludedLineIndices: patchLineIndices, + FileNameOverride: file.GetPath(), + }). + FormatPlain() + if patchToApply == "" { + return nil + } + + return self.c.Git().Patch.ApplyPatch(patchToApply, opts) +} diff --git a/pkg/gui/types/context.go b/pkg/gui/types/context.go index 2ed28dd17..f468687d9 100644 --- a/pkg/gui/types/context.go +++ b/pkg/gui/types/context.go @@ -239,6 +239,24 @@ type FocusedMainViewDiffSource interface { PlainDiff(pane DiffPaneContext, paths []string) string } +// FocusedMainViewActions describes what a side panel does when the user acts on a +// selection of diff lines in the focused main view. The main view owns the selection +// and the keys; what acting on it means is the panel's business, e.g. the working +// tree panel stages and unstages. +// +// It extends the diff source rather than standing beside it, because acting on a +// selection needs the diff behind the rendering just as reading it does; a panel that +// implements only the source offers a diff to read and copy but nothing to do to it. +type FocusedMainViewActions interface { + FocusedMainViewDiffSource + + // PrimaryAction acts on the diff lines in the inclusive buffer-line range that the + // current selection in the given pane covers (see View.SelectedBufferLineRange): a + // single line, a range, or a hunk. The panel re-renders the diff itself, being the + // one that knows what it did to it. + PrimaryAction(pane DiffPaneContext, firstBufferLine int, lastBufferLine int) error +} + type IListContext interface { Context diff --git a/pkg/integration/tests/main_view/no_selection_over_a_binary_diff.go b/pkg/integration/tests/main_view/no_selection_over_a_binary_diff.go index 332b52b14..2405902ed 100644 --- a/pkg/integration/tests/main_view/no_selection_over_a_binary_diff.go +++ b/pkg/integration/tests/main_view/no_selection_over_a_binary_diff.go @@ -6,16 +6,18 @@ import ( ) var NoSelectionOverABinaryDiff = NewIntegrationTest(NewIntegrationTestArgs{ - Description: "A diff with nothing selectable in it shows no selection, and a refresh doesn't bring one", + Description: "A diff with nothing selectable in it shows no selection, however it came to be showing", ExtraCmdArgs: []string{}, Skip: false, SetupConfig: func(cfg *config.AppConfig) { cfg.GetUserConfig().Gui.UseHunkModeInStagingView = false }, SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("text", "one\ntwo\nthree\n") shell.CreateFileAndAdd("binary", "\x00one\x00two\x00") shell.Commit("one") + shell.UpdateFile("text", "one\nTWO\nthree\n") shell.UpdateFile("binary", "\x00one\x00TWO\x00") }, Run: func(t *TestDriver, keys config.KeybindingConfig) { @@ -23,6 +25,7 @@ var NoSelectionOverABinaryDiff = NewIntegrationTest(NewIntegrationTestArgs{ // refresh, which renders the same diff again, doesn't make one appear. t.Views().Files(). IsFocused(). + NavigateToLine(Contains("binary")). Press(keys.Universal.FocusMainView) t.Views().Main(). @@ -32,5 +35,22 @@ var NoSelectionOverABinaryDiff = NewIntegrationTest(NewIntegrationTestArgs{ t.GlobalPress(keys.Universal.Refresh) }). SelectionIsHidden() + + // The same when acting on a diff of several files leaves nothing selectable in + // it: staging the text file's only change leaves the binary one behind. + t.Views().Files(). + Focus(). + NavigateToLine(Contains("▼ /")). + Press(keys.Universal.FocusMainView) + + t.Views().Main(). + IsFocused(). + SelectionIsActive(). + SelectedLines( + Contains("-two"), + ). + Press(keys.Main.ToggleSelectHunk). + PressPrimaryAction(). + SelectionIsHidden() }, }) diff --git a/pkg/integration/tests/main_view/stage_diff_lines.go b/pkg/integration/tests/main_view/stage_diff_lines.go new file mode 100644 index 000000000..6ce83e03e --- /dev/null +++ b/pkg/integration/tests/main_view/stage_diff_lines.go @@ -0,0 +1,70 @@ +package main_view + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var StageDiffLines = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Stage a line and a hunk of the working tree's diff from the focused main view", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInStagingView = false + }, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("file1", "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\nnine\nten\n") + shell.Commit("one") + + // Two change blocks, far enough apart to stay separate hunks. + shell.UpdateFile("file1", "one\ntwo\nADD1\nADD2\nthree\nfour\nfive\nsix\nseven\neight\nNINE\nten\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Files(). + IsFocused(). + Lines( + Contains("file1").IsSelected(), + ). + Press(keys.Universal.FocusMainView) + + // A single line goes into the index by itself, leaving the rest of its block + // unstaged — which is the whole point of staging from the diff. + t.Views().Main(). + IsFocused(). + SelectedLines( + Contains("+ADD1"), + ). + PressPrimaryAction() + + t.Views().Files().Lines( + Contains("MM file1"), + ) + t.Views().Secondary(). + ContainsLines( + Contains("+ADD1"), + ). + Content(DoesNotContain("+ADD2")) + t.Views().Main(). + Content(DoesNotContain("+ADD1")). + ContainsLines( + Contains("+ADD2"), + ) + + // A whole change block goes in one press. + t.Views().Main(). + IsFocused(). + NavigateToLine(Contains("-nine")). + Press(keys.Main.ToggleSelectHunk). + SelectedLines( + Contains("-nine"), + Contains("+NINE"), + ). + PressPrimaryAction() + + t.Views().Secondary().ContainsLines( + Contains("-nine"), + Contains("+NINE"), + ) + t.Views().Main().Content(DoesNotContain("NINE")) + }, +}) diff --git a/pkg/integration/tests/main_view/stage_diff_lines_of_a_path_with_a_space.go b/pkg/integration/tests/main_view/stage_diff_lines_of_a_path_with_a_space.go new file mode 100644 index 000000000..f50b4e7b9 --- /dev/null +++ b/pkg/integration/tests/main_view/stage_diff_lines_of_a_path_with_a_space.go @@ -0,0 +1,52 @@ +package main_view + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var StageDiffLinesOfAPathWithASpace = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Stage a line of a file whose path contains a space from the focused main view", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInStagingView = false + }, + SetupRepo: func(shell *Shell) { + // git ends the path field of the diff's "---" and "+++" lines with a tab + // when the path contains a space, and the view shows the tab as spaces. + shell.CreateFileAndAdd("my file", "one\ntwo\nthree\n") + shell.Commit("one") + + shell.UpdateFile("my file", "one\nADD1\nADD2\ntwo\nthree\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Files(). + IsFocused(). + Lines( + Contains("my file").IsSelected(), + ). + Press(keys.Universal.FocusMainView) + + t.Views().Main(). + IsFocused(). + SelectedLines( + Contains("+ADD1"), + ). + PressPrimaryAction() + + t.Views().Files().Lines( + Contains("MM my file"), + ) + t.Views().Secondary(). + ContainsLines( + Contains("+ADD1"), + ). + Content(DoesNotContain("+ADD2")) + t.Views().Main(). + Content(DoesNotContain("+ADD1")). + ContainsLines( + Contains("+ADD2"), + ) + }, +}) diff --git a/pkg/integration/tests/main_view/stage_range_spanning_files.go b/pkg/integration/tests/main_view/stage_range_spanning_files.go new file mode 100644 index 000000000..70f614229 --- /dev/null +++ b/pkg/integration/tests/main_view/stage_range_spanning_files.go @@ -0,0 +1,55 @@ +package main_view + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var StageRangeSpanningFiles = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Stage a range reaching from one file's diff into another's, in a directory's focused main view", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInStagingView = false + }, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("fileA", "a\n") + shell.CreateFileAndAdd("fileB", "b\n") + shell.CreateFileAndAdd("fileC", "c\n") + shell.Commit("one") + + shell.UpdateFile("fileA", "a\nfromA\n") + shell.UpdateFile("fileB", "b\nfromB\n") + shell.UpdateFile("fileC", "c\nfromC\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + // With the root of the tree selected, the main view shows all three files' diffs. + t.Views().Files(). + IsFocused(). + Lines( + Contains("▼ /").IsSelected(), + Contains(" M fileA"), + Contains(" M fileB"), + Contains(" M fileC"), + ). + Press(keys.Universal.FocusMainView) + + t.Views().Main(). + IsFocused(). + SelectedLines( + Contains("+fromA"), + ). + Press(keys.Universal.ToggleRangeSelect). + NavigateToLine(Contains("+fromB")). + PressPrimaryAction() + + // Both files the range reached into are staged, each by its own patch, and the + // file below it is untouched. + t.Views().Files().Lines( + Contains("▼ /"), + Contains("M fileA"), + Contains("M fileB"), + Contains(" M fileC"), + ) + }, +}) diff --git a/pkg/integration/tests/main_view/unstage_diff_lines.go b/pkg/integration/tests/main_view/unstage_diff_lines.go new file mode 100644 index 000000000..41f631b0e --- /dev/null +++ b/pkg/integration/tests/main_view/unstage_diff_lines.go @@ -0,0 +1,57 @@ +package main_view + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var UnstageDiffLines = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Take a line back out of the index from the staged half of the focused main view", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInStagingView = false + }, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("file1", "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\nnine\nten\n") + shell.Commit("one") + + // Two staged additions, far enough apart to be separate hunks, plus an unstaged + // one, so that the diff is split into a staged and an unstaged half. + shell.UpdateFileAndAdd("file1", "one\nSTAGED1\ntwo\nthree\nfour\nfive\nsix\nseven\nSTAGED2\neight\nnine\nten\n") + shell.UpdateFile("file1", "one\nSTAGED1\ntwo\nthree\nUNSTAGED\nfour\nfive\nsix\nseven\nSTAGED2\neight\nnine\nten\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Files(). + IsFocused(). + Lines( + Contains("MM file1").IsSelected(), + ). + Press(keys.Universal.FocusMainView) + + // The main half holds the unstaged changes; the staged ones are next door. + t.Views().Main(). + IsFocused(). + SelectedLines( + Contains("+UNSTAGED"), + ). + Press(keys.Universal.TogglePanel) + + t.Views().Secondary(). + IsFocused(). + SelectedLines( + Contains("+STAGED1"), + ). + PressPrimaryAction() + + // The line acted on is out of the index, and the one below it stays in. + t.Views().Secondary(). + Content(DoesNotContain("+STAGED1")). + ContainsLines( + Contains("+STAGED2"), + ) + t.Views().Main().ContainsLines( + Contains("+STAGED1"), + ) + }, +}) diff --git a/pkg/integration/tests/test_list.go b/pkg/integration/tests/test_list.go index a46d8fcf4..9a1a61bd8 100644 --- a/pkg/integration/tests/test_list.go +++ b/pkg/integration/tests/test_list.go @@ -409,6 +409,10 @@ var tests = []*components.IntegrationTest{ main_view.SelectVisibleHunkOnFocusingMainView, main_view.SelectionCommandsOnlyWhereTheyApply, main_view.SelectionOverTheCustomPatch, + main_view.StageDiffLines, + main_view.StageDiffLinesOfAPathWithASpace, + main_view.StageRangeSpanningFiles, + main_view.UnstageDiffLines, misc.ConfirmOnQuit, misc.CopyConfirmationMessageToClipboard, misc.CopyToClipboard, From 9132730229d490d9a87716ea00f01eea37db4fa5 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Sun, 16 Aug 2026 14:05:00 +0200 Subject: [PATCH 03/21] Act on a whole file's changes as acting on the file The diff of a deleted file is its content going away, so putting every line of it into the index leaves an empty file there (modified in the index, deleted in the working tree) rather than the deletion the user selected. The reverse case matches: the diff of an added file is its whole content, and taking all of it back out of the index leaves the file tracked and empty rather than untracked again. In the staging view you had to enter such a file deliberately to reach these cases, but stepping through a directory's diff hunk by hunk runs into them routinely. Selecting every change of a file says "this file", so stage or unstage the file itself. This applies to any file, since applying a file's whole diff amounts to the same thing everywhere else. Co-authored-by: Claude Opus 5 (1M context) --- .../controllers/working_tree_diff_actions.go | 21 +++++ .../tests/main_view/stage_deleted_file.go | 80 +++++++++++++++++++ pkg/integration/tests/test_list.go | 1 + 3 files changed, 102 insertions(+) create mode 100644 pkg/integration/tests/main_view/stage_deleted_file.go diff --git a/pkg/gui/controllers/working_tree_diff_actions.go b/pkg/gui/controllers/working_tree_diff_actions.go index e75d538f2..32bcd60db 100644 --- a/pkg/gui/controllers/working_tree_diff_actions.go +++ b/pkg/gui/controllers/working_tree_diff_actions.go @@ -171,6 +171,19 @@ func (self *WorkingTreeDiffActions) applyDiffLines( } } + // Acting on every change of a file is acting on the file itself, and saying so is + // not the same as applying its diff. The diff of a deleted file is its content + // going away, and putting that into the index line by line leaves an empty file + // there rather than the deletion; the diff of an added one is its whole content, + // and taking that back out leaves an empty file in the index rather than an + // untracked one. + if opts.Cached && len(patchLineIndices) == changeLineCount(parsedPatch) { + if opts.Reverse { + return self.c.Git().WorkingTree.UnStageFile(file.Names(), file.Tracked) + } + return self.c.Git().WorkingTree.StageFile(file.GetPath()) + } + patchToApply := parsedPatch. Transform(patch.TransformOpts{ Reverse: opts.Reverse, @@ -184,3 +197,11 @@ func (self *WorkingTreeDiffActions) applyDiffLines( return self.c.Git().Patch.ApplyPatch(patchToApply, opts) } + +// changeLineCount returns how many of a patch's lines are changes rather than context +// or header. A selection of the whole diff covers exactly that many. +func changeLineCount(p *patch.Patch) int { + return lo.CountBy(p.Lines(), func(line *patch.PatchLine) bool { + return line.IsAddition() || line.IsDeletion() + }) +} diff --git a/pkg/integration/tests/main_view/stage_deleted_file.go b/pkg/integration/tests/main_view/stage_deleted_file.go new file mode 100644 index 000000000..9b863ae72 --- /dev/null +++ b/pkg/integration/tests/main_view/stage_deleted_file.go @@ -0,0 +1,80 @@ +package main_view + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var StageDeletedFile = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Acting on the whole of a file's block in a directory's diff acts on the file: staging a deletion, and unstaging an addition", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInStagingView = false + }, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("fileA", "a\n") + shell.CreateFileAndAdd("fileB", "b1\nb2\n") + shell.Commit("one") + + shell.UpdateFile("fileA", "a\nfromA\n") + shell.DeleteFile("fileB") + shell.CreateFileAndAdd("fileC", "c1\nc2\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Files(). + IsFocused(). + Lines( + Contains("▼ /").IsSelected(), + Contains(" M fileA"), + Contains(" D fileB"), + Contains("A fileC"), + ). + Press(keys.Universal.FocusMainView) + + // Select everything the deleted file contributes to the diff. + t.Views().Main(). + IsFocused(). + NavigateToLine(Contains("-b1")). + Press(keys.Universal.ToggleRangeSelect). + NavigateToLine(Contains("-b2")). + SelectedLines( + Contains("-b1"), + Contains("-b2"), + ). + PressPrimaryAction() + + // The file is staged as deleted. Applying its lines as a patch would have left + // an empty file in the index instead, which is not what deleting a file means. + t.Views().Files().Lines( + Contains("▼ /"), + Contains(" M fileA"), + Contains("D fileB"), + Contains("A fileC"), + ) + + // The same the other way round: taking the whole of an added file back out of + // the index leaves it untracked, rather than tracked and empty. + t.Views().Main(). + IsFocused(). + Press(keys.Universal.TogglePanel) + + t.Views().Secondary(). + IsFocused(). + NavigateToLine(Contains("+c1")). + Press(keys.Universal.ToggleRangeSelect). + NavigateToLine(Contains("+c2")). + SelectedLines( + Contains("+c1"), + Contains("+c2"), + ). + PressPrimaryAction() + + t.Views().Files().Lines( + Contains("▼ /"), + Contains(" M fileA"), + Contains("D fileB"), + Contains("?? fileC"), + ) + }, +}) diff --git a/pkg/integration/tests/test_list.go b/pkg/integration/tests/test_list.go index 9a1a61bd8..9d84e7d25 100644 --- a/pkg/integration/tests/test_list.go +++ b/pkg/integration/tests/test_list.go @@ -409,6 +409,7 @@ var tests = []*components.IntegrationTest{ main_view.SelectVisibleHunkOnFocusingMainView, main_view.SelectionCommandsOnlyWhereTheyApply, main_view.SelectionOverTheCustomPatch, + main_view.StageDeletedFile, main_view.StageDiffLines, main_view.StageDiffLinesOfAPathWithASpace, main_view.StageRangeSpanningFiles, From b1566a5e68b5f09c1c2469ee8356f2e247987884 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Sun, 16 Aug 2026 06:42:06 +0200 Subject: [PATCH 04/21] Extract the shared core of the diff-line restores MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Putting a view back on a remembered line as it re-renders is two things: the plumbing that watches the content arrive, reveals it at the right moment and places the view, and the search that says which row to land on. Only the second is specific to what is being remembered, and a second kind of it is about to arrive — the change line an action leaves the selection on, which is found by counting rather than by identity. Behaviour-preserving. Co-authored-by: Claude Opus 5 (1M context) --- .../controllers/helpers/diff_line_restore.go | 77 +++++++++++++++---- 1 file changed, 62 insertions(+), 15 deletions(-) diff --git a/pkg/gui/controllers/helpers/diff_line_restore.go b/pkg/gui/controllers/helpers/diff_line_restore.go index 7a35d7638..c11364998 100644 --- a/pkg/gui/controllers/helpers/diff_line_restore.go +++ b/pkg/gui/controllers/helpers/diff_line_restore.go @@ -230,20 +230,68 @@ func (self *DiffLineHelper) findDiffLine(view *gocui.View, identity types.DiffLi func (self *DiffLineHelper) restoreDiffLinePositionOnRerender( view *gocui.View, candidates []diffLineAnchor, place func(anchor diffLineAnchor, viewLine int), ) { - manager := self.c.GetViewBufferManagerForView(view) - if manager == nil || len(candidates) == 0 { + if len(candidates) == 0 { return } - // The readiness check below runs on the task's own goroutine, where neither the - // view's dimensions nor the repo we are in may be read — a repo switch replaces - // the latter — so take both here, on the UI thread, for it to work from. - viewHeight := view.InnerHeight() + // The search of the loading content runs on the task's own goroutine, where the + // repo we are in may not be read — a repo switch replaces it — so take it here, on + // the UI thread, for the search to work from. worktreePath := self.c.Git().RepoPaths.WorktreePath() + // Which candidate the search settled on, for place to put back where it was. + found := diffLineAnchor{} + + self.installDiffLineRestore(view, + func(rows []gocui.DiffLineContent, offset int) (int, bool) { + for i, row := range rows { + if rowShowsDiffLine(row, worktreePath, candidates[0].identity) { + found = candidates[0] + return offset + i, true + } + } + return 0, false + }, + func(contents []gocui.DiffLineContent) (int, bool) { + anchor, bufferLine := self.nearestSurvivingCandidate(contents, candidates) + if bufferLine == -1 { + return 0, false + } + found = anchor + return bufferLine, true + }, + func(viewLine int) { place(found, viewLine) }, + ) +} + +// installDiffLineRestore is what the restores are built on: it arranges for view's +// next re-render to be revealed with the row a search finds in it placed by place, +// instead of from the top. +// +// The search comes in two halves, because the content arrives a line at a time. +// findEarly is given the rows that have loaded since it last looked, so that the +// re-render can be revealed as soon as the row is there rather than waiting for the +// rest of a long diff; it can only go by what the renderer states about a row, a +// partly-loaded diff being unparseable. findComplete is given the whole rendering at +// the swap, for a target the incremental search couldn't settle on. Either returns the +// buffer line it found, and place is not called at all when neither does. +func (self *DiffLineHelper) installDiffLineRestore( + view *gocui.View, + findEarly func(rows []gocui.DiffLineContent, offset int) (int, bool), + findComplete func(contents []gocui.DiffLineContent) (int, bool), + place func(viewLine int), +) { + manager := self.c.GetViewBufferManagerForView(view) + if manager == nil { + return + } + + // The readiness check below runs on the task's own goroutine, which may not read + // the view's dimensions, so take them here, on the UI thread. + viewHeight := view.InnerHeight() + // What the search of the loading content has found, and how far it has looked, so // that each line is looked at once. - found := diffLineAnchor{} foundLine := -1 scanned := 0 @@ -251,11 +299,8 @@ func (self *DiffLineHelper) restoreDiffLinePositionOnRerender( FirstPaintReady: func() bool { if foundLine == -1 { rows := view.OffscreenDiffLineContentsFrom(scanned) - for i, row := range rows { - if rowShowsDiffLine(row, worktreePath, candidates[0].identity) { - found, foundLine = candidates[0], scanned+i - break - } + if bufferLine, ok := findEarly(rows, scanned); ok { + foundLine = bufferLine } scanned += len(rows) if foundLine == -1 { @@ -267,9 +312,11 @@ func (self *DiffLineHelper) restoreDiffLinePositionOnRerender( return view.OffscreenLineCount() >= foundLine+viewHeight }, Apply: func(swapIn func()) bool { - anchor, bufferLine := found, foundLine + bufferLine := foundLine if bufferLine == -1 { - anchor, bufferLine = self.nearestSurvivingCandidate(view.OffscreenDiffLineContents(), candidates) + if line, ok := findComplete(view.OffscreenDiffLineContents()); ok { + bufferLine = line + } } swapIn() @@ -281,7 +328,7 @@ func (self *DiffLineHelper) restoreDiffLinePositionOnRerender( if !ok { return false } - place(anchor, viewLine) + place(viewLine) return true }, }) From 8dddf9f4291e95c46673f43a9a5fbf99d4ea7c23 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Sun, 16 Aug 2026 06:44:34 +0200 Subject: [PATCH 05/21] Carry the selection to the next change after staging MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Staging takes the lines it acted on out of the diff, so the selection has nothing to sit on afterwards and would be left wherever those lines used to be. What the user wants is the change that moved up into their place, so that pressing the key again goes on to the next one — which is how staging line by line through a file works. The line acted on is gone, so it can't be remembered by identity the way a re-render of the same diff remembers one; what is remembered instead is its place in the sequence of the diff's changes, which the change after it inherits. Staging the last change is the one case with nothing to inherit it, and there the selection stays on the last change there is. Co-authored-by: Claude Opus 5 (1M context) --- .../controllers/helpers/diff_line_helper.go | 12 ++++ .../controllers/helpers/diff_line_restore.go | 59 +++++++++++++++++++ pkg/gui/controllers/main_view_controller.go | 36 ++++++++++- .../controllers/working_tree_diff_actions.go | 10 +++- .../select_next_change_after_staging.go | 54 +++++++++++++++++ pkg/integration/tests/test_list.go | 1 + 6 files changed, 168 insertions(+), 4 deletions(-) create mode 100644 pkg/integration/tests/main_view/select_next_change_after_staging.go diff --git a/pkg/gui/controllers/helpers/diff_line_helper.go b/pkg/gui/controllers/helpers/diff_line_helper.go index b648ce207..95f95cc59 100644 --- a/pkg/gui/controllers/helpers/diff_line_helper.go +++ b/pkg/gui/controllers/helpers/diff_line_helper.go @@ -86,6 +86,18 @@ func (self *DiffLineHelper) diffLineIdentitiesFromRecords(metadata []string) []t return self.diffLineInfos(parseDiffLineRecords(metadata)) } +// diffLineInfoFromRecords recovers a row's own identity from the records the diff +// renderer stated for it. That is the line the row leads with, of the ones +// diffLineIdentitiesFromRecords finds on it. ok is false when the row carries no +// record we understand. +func (self *DiffLineHelper) diffLineInfoFromRecords(metadata []string) (types.DiffLineInfo, bool) { + identities := self.diffLineIdentitiesFromRecords(metadata) + if len(identities) == 0 { + return types.DiffLineInfo{}, false + } + return identities[0], true +} + // resolvedDiffLine is one rendered row's recovered identity, plus whether it could // be recovered at all — the element of the table resolveDiffLines produces. type resolvedDiffLine struct { diff --git a/pkg/gui/controllers/helpers/diff_line_restore.go b/pkg/gui/controllers/helpers/diff_line_restore.go index c11364998..24843a396 100644 --- a/pkg/gui/controllers/helpers/diff_line_restore.go +++ b/pkg/gui/controllers/helpers/diff_line_restore.go @@ -264,6 +264,65 @@ func (self *DiffLineHelper) restoreDiffLinePositionOnRerender( ) } +// ChangeLineOrdinal returns how many change lines of view's rendered diff come before +// the given buffer line — that line's place in the sequence of changes. +// +// It is how a place in a diff is remembered across acting on it: an action consumes +// the lines it acted on, so the identity of the line the user was on is gone, but the +// place it left behind is the same one that identity used to have. +func (self *DiffLineHelper) ChangeLineOrdinal(view *gocui.View, bufferLine int) int { + ordinal := 0 + for i, row := range self.resolveDiffLines(view.DiffLineContents()) { + if i >= bufferLine { + break + } + if row.ok && row.info.IsChange() { + ordinal++ + } + } + return ordinal +} + +// RevealChangeLineAtOrdinal arranges for view's next re-render to be shown with the +// change line at the given ordinal placed by place — the diff having changed under the +// user, this is where what they were doing carries on. When the new diff has fewer +// changes than that, because the ones acted on were its last, it lands on the last +// change left. +func (self *DiffLineHelper) RevealChangeLineAtOrdinal(view *gocui.View, ordinal int, place func(viewLine int)) { + // How many change lines the incremental search has passed, so that it can carry on + // counting where it left off. + seen := 0 + + self.installDiffLineRestore(view, + func(rows []gocui.DiffLineContent, offset int) (int, bool) { + for i, row := range rows { + if info, ok := self.diffLineInfoFromRecords(row.Metadata); ok && info.IsChange() { + if seen == ordinal { + return offset + i, true + } + seen++ + } + } + return 0, false + }, + func(contents []gocui.DiffLineContent) (int, bool) { + last, count := -1, 0 + for i, row := range self.resolveDiffLines(contents) { + if !row.ok || !row.info.IsChange() { + continue + } + if count == ordinal { + return i, true + } + count++ + last = i + } + return last, last != -1 + }, + place, + ) +} + // installDiffLineRestore is what the restores are built on: it arranges for view's // next re-render to be revealed with the row a search finds in it placed by place, // instead of from the top. diff --git a/pkg/gui/controllers/main_view_controller.go b/pkg/gui/controllers/main_view_controller.go index b814ea0fa..f8fcaa4da 100644 --- a/pkg/gui/controllers/main_view_controller.go +++ b/pkg/gui/controllers/main_view_controller.go @@ -300,6 +300,36 @@ func (self *MainViewController) primaryAction() error { return actions.PrimaryAction(self.context, first, last) } +// revealSelectionAfterAction moves the focused main view's selection to the change +// that takes the place of the one just acted on, once the changed diff has re-rendered. +// Call it from the panel's action handler with the pane it acted in and the buffer line +// the selection starts on, before triggering the re-render. +// +// The line acted on is gone from the diff, so what is remembered is its place among the +// diff's changes: the next change moves up into it, which is where you want to be to +// carry on. A range collapses to a single line at its start, and hunk mode selects the +// whole block it lands in, so that pressing the key again acts on the next hunk. +func revealSelectionAfterAction(c *ControllerCommon, pane types.DiffPaneContext, firstBufferLine int) { + view := pane.GetView() + ordinal := c.Helpers().DiffLine.ChangeLineOrdinal(view, firstBufferLine) + + sel := pane.DiffSelectState() + if sel.Mode == types.DiffSelectModeRange { + sel.Mode = types.DiffSelectModeLine + sel.RangeIsSticky = false + } + selectHunk := sel.Mode == types.DiffSelectModeHunk + + c.Helpers().DiffLine.RevealChangeLineAtOrdinal(view, ordinal, func(viewLine int) { + if selectHunk { + selectDiffHunk(c, pane, viewLine, true) + return + } + view.CancelRangeSelect() + showSelectionAtLine(view, viewLine, true) + }) +} + // workingTreeActionDescription gives a command's description only where the command // applies — over the working tree's diff — so that it is listed there and nowhere else. func (self *MainViewController) workingTreeActionDescription(description string) func() string { @@ -622,12 +652,12 @@ func (self *MainViewController) selectHunkAround(changeViewLine int, scrollIntoV // to go there; a click leaves it false, so that the view doesn't move under the mouse // when the block the click landed in starts above the viewport. func selectDiffHunk( - c *ControllerCommon, mainContext *context.MainContext, changeViewLine int, scrollIntoView bool, + c *ControllerCommon, pane types.DiffPaneContext, changeViewLine int, scrollIntoView bool, ) { - view := mainContext.GetView() + view := pane.GetView() start, end, ok := c.Helpers().DiffLine.ChangeBlockBounds(view, changeViewLine) if !ok { - mainContext.DiffSelectState().Mode = types.DiffSelectModeLine + pane.DiffSelectState().Mode = types.DiffSelectModeLine view.CancelRangeSelect() showSelectionAtLine(view, changeViewLine, scrollIntoView) return diff --git a/pkg/gui/controllers/working_tree_diff_actions.go b/pkg/gui/controllers/working_tree_diff_actions.go index 32bcd60db..2cc5a0282 100644 --- a/pkg/gui/controllers/working_tree_diff_actions.go +++ b/pkg/gui/controllers/working_tree_diff_actions.go @@ -66,7 +66,7 @@ func (self *WorkingTreeDiffActions) PrimaryAction(pane types.DiffPaneContext, fi // Either way the patch goes to the index: forwards from the unstaged side to stage // it, backwards from the staged side to take it back out. - return self.applyDiffLineSelection(infos, onStagedSide, + return self.applyDiffLineSelection(pane, firstBufferLine, infos, onStagedSide, git_commands.ApplyPatchOpts{Reverse: onStagedSide, Cached: true}) } @@ -88,7 +88,10 @@ func (self *WorkingTreeDiffActions) diffLineSelection( // applyDiffLineSelection applies the selected change lines, a patch per file, and // re-renders what that changed. onStagedSide says which of the file's two diffs the // lines were selected in and so are to be found in; opts says how to apply them. +// firstBufferLine is where the selection started, which is where the work carries on +// from once the diff has changed under it. func (self *WorkingTreeDiffActions) applyDiffLineSelection( + pane types.DiffPaneContext, firstBufferLine int, infos []types.DiffLineInfo, onStagedSide bool, opts git_commands.ApplyPatchOpts, ) error { self.c.LogAction(self.c.Tr.Actions.ApplyPatch) @@ -106,6 +109,11 @@ func (self *WorkingTreeDiffActions) applyDiffLineSelection( } } + // The refresh below queues the re-render of the diff we just changed; this rides it, + // so that the selection ends up on the change that took the place of the one acted + // on rather than at a position that means nothing any more. + revealSelectionAfterAction(self.c, pane, firstBufferLine) + // Block input until the refresh has landed, so that a quick second keypress acts on // the diff as it now is rather than on the one we just changed. self.c.RefreshBlockingInput(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}}) diff --git a/pkg/integration/tests/main_view/select_next_change_after_staging.go b/pkg/integration/tests/main_view/select_next_change_after_staging.go new file mode 100644 index 000000000..81033247c --- /dev/null +++ b/pkg/integration/tests/main_view/select_next_change_after_staging.go @@ -0,0 +1,54 @@ +package main_view + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var SelectNextChangeAfterStaging = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "After staging from the focused main view the selection lands on the change that took the place of the one staged", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInStagingView = false + }, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("file1", "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\nnine\nten\n") + shell.Commit("one") + + shell.UpdateFile("file1", "one\nADD1\nADD2\ntwo\nthree\nfour\nfive\nsix\nseven\neight\nNINE\nten\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Files(). + IsFocused(). + Press(keys.Universal.FocusMainView) + + // Line by line, each press leaves the selection on the next change to stage. + t.Views().Main(). + IsFocused(). + SelectedLines( + Contains("+ADD1"), + ). + PressPrimaryAction(). + SelectedLines( + Contains("+ADD2"), + ). + PressPrimaryAction(). + SelectedLines( + Contains("-nine"), + ). + // A hunk goes the same way: the block after the one staged takes its place, + // and here there is none, so the last change stays selected. + Press(keys.Main.ToggleSelectHunk). + SelectedLines( + Contains("-nine"), + Contains("+NINE"), + ). + PressPrimaryAction(). + Tap(func() { + t.Views().Files().Lines( + Contains("M file1"), + ) + }) + }, +}) diff --git a/pkg/integration/tests/test_list.go b/pkg/integration/tests/test_list.go index 9d84e7d25..cc6572f2e 100644 --- a/pkg/integration/tests/test_list.go +++ b/pkg/integration/tests/test_list.go @@ -405,6 +405,7 @@ var tests = []*components.IntegrationTest{ main_view.SelectHunkOnFocusingMainView, main_view.SelectInADiffReadInPart, main_view.SelectLineWhenWholeFileIsOneHunk, + main_view.SelectNextChangeAfterStaging, main_view.SelectVisibleChangeOnFocusingMainView, main_view.SelectVisibleHunkOnFocusingMainView, main_view.SelectionCommandsOnlyWhereTheyApply, From cc09f92488881b08ab58116ac255f06f6b7ed8cf Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 18 Aug 2026 18:47:03 +0200 Subject: [PATCH 06/21] Give the focused main view's selection a home outside the controllers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Where the selection starts out, and how it widens to a whole change block, are questions about what the view is showing — the same rendered diff the queries next door read. Nothing about them belongs to a keybinding, and the render funnel is about to need them too, from a layer that can reach a helper but not a controller. Co-authored-by: Claude Opus 5 (1M context) --- .../controllers/helpers/diff_line_queries.go | 11 -- .../helpers/diff_line_selection.go | 133 ++++++++++++++++++ pkg/gui/controllers/main_view_controller.go | 129 ++--------------- .../switch_to_focused_main_view_controller.go | 2 +- 4 files changed, 143 insertions(+), 132 deletions(-) create mode 100644 pkg/gui/controllers/helpers/diff_line_selection.go diff --git a/pkg/gui/controllers/helpers/diff_line_queries.go b/pkg/gui/controllers/helpers/diff_line_queries.go index 1f623b937..a7b8874e6 100644 --- a/pkg/gui/controllers/helpers/diff_line_queries.go +++ b/pkg/gui/controllers/helpers/diff_line_queries.go @@ -223,17 +223,6 @@ func (self *DiffLineHelper) ChangeBlockBounds(view *gocui.View, anchorViewLine i return startView, endView, true } -// SelectedHunkBounds returns the change block selected in hunk mode. The range -// anchor stays on the block's far end when a click moves the cursor before its -// handler runs, so it still identifies the selected block. -func (self *DiffLineHelper) SelectedHunkBounds(view *gocui.View) (int, int, bool) { - anchor := view.RangeSelectStartY() - if anchor < 0 { - return 0, 0, false - } - return self.ChangeBlockBounds(view, anchor) -} - // AdjacentChangeBlock returns the view line to move to for next/previous change-block // navigation in view's rendered diff, starting from anchorViewLine. A change block is // lazygit's notion of a hunk (see ChangeBlockBounds). forward=true targets the start diff --git a/pkg/gui/controllers/helpers/diff_line_selection.go b/pkg/gui/controllers/helpers/diff_line_selection.go new file mode 100644 index 000000000..1b42cc181 --- /dev/null +++ b/pkg/gui/controllers/helpers/diff_line_selection.go @@ -0,0 +1,133 @@ +package helpers + +import ( + "github.com/jesseduffield/lazygit/pkg/gocui" + "github.com/jesseduffield/lazygit/pkg/gui/context" + "github.com/jesseduffield/lazygit/pkg/gui/types" + "github.com/samber/lo" +) + +// Putting a selection in the focused main view: where it starts out, and how it is +// widened to a whole change block. Both are answered from what the view is showing, +// as recovered by the queries next door. + +// EstablishSelection turns on the focused main view's selection once the view has +// been focused. clickedViewLine is the view line a click pointed at, or -1 for +// keyboard focus, which points at no particular line and so starts at the first +// change line on screen. +// +// Focusing never moves the view: you focus the diff you are reading in order to point +// at something in it, so the selection goes where you are looking rather than the +// view going where the selection would like to be. With no change line on screen at +// all — a long stretch of context — it lands on the middle visible line, the likeliest +// one to be the one being read. +// +// With hunk mode configured as the default the selection widens to the whole change +// block: keyboard focus lands on the first block on screen, and a click on a change +// line selects that line's block, ready to act on. A click on context still selects +// just that line — the click points at it precisely, so it stays editable. +func (self *DiffLineHelper) EstablishSelection(mainContext *context.MainContext, clickedViewLine int) { + mainContext.ResetDiffSelectMode() + view := mainContext.GetView() + + // The panel beneath renders a diff, but that diff may hold nothing to act on: a + // binary file, or an empty commit. Rendering it worked that out, so the pane is + // already showing no selection and there is nowhere to put one. + if !self.ViewHasChangeLines(view) { + return + } + + if clickedViewLine >= 0 { + // Remember where the click landed so that a drag that follows anchors its range + // there, even when this click selects a whole hunk. + mainContext.SetDragAnchorViewLine(clickedViewLine) + if self.hunkModeApplies(view, clickedViewLine) && self.IsChangeLine(view, clickedViewLine) { + mainContext.DiffSelectState().Mode = types.DiffSelectModeHunk + self.SelectChangeBlock(mainContext, clickedViewLine, false) + return + } + self.ShowSelectionAtLine(view, clickedViewLine, false) + return + } + + target, ok := self.changeToSelectOnScreen(view) + if !ok { + self.ShowSelectionAtLine(view, view.MiddleVisibleLineIdx(), false) + return + } + if self.hunkModeApplies(view, target) { + mainContext.DiffSelectState().Mode = types.DiffSelectModeHunk + self.SelectChangeBlock(mainContext, target, false) + return + } + self.ShowSelectionAtLine(view, target, false) +} + +// changeToSelectOnScreen returns the change line keyboard focus establishes the +// selection on. In hunk mode that is the first block that begins on screen, so that +// the block being offered up is one the user can see the extent of, falling back to a +// block that reaches into the view from above — a change longer than the screen, where +// there is nothing else to offer. Line by line it is simply the first change line on +// screen. ok is false when the viewport shows no change at all. +func (self *DiffLineHelper) changeToSelectOnScreen(view *gocui.View) (int, bool) { + if self.c.UserConfig().Gui.UseHunkModeInStagingView { + return self.FirstChangeBlockInView(view) + } + return self.FirstChangeLineInView(view) +} + +// hunkModeApplies reports whether an established selection should start out as the +// whole change block around the given change line. That's what the config asks for, +// except over a file shown as one solid block of changes, where it would select the +// whole file — see IsSingleHunkForWholeFile. +func (self *DiffLineHelper) hunkModeApplies(view *gocui.View, changeViewLine int) bool { + return self.c.UserConfig().Gui.UseHunkModeInStagingView && + !self.IsSingleHunkForWholeFile(view, changeViewLine) +} + +// ShowSelectionAtLine moves the focused main view's selection to the given view line, +// clamped to the content. scrollIntoView scrolls the line into view when it's +// off-screen, for navigating to it; a click leaves it false, the clicked line being on +// screen already. +func (self *DiffLineHelper) ShowSelectionAtLine(view *gocui.View, lineIdx int, scrollIntoView bool) { + view.FocusPoint(0, lo.Clamp(lineIdx, 0, max(0, view.ViewLinesHeight()-1)), scrollIntoView) + + // A search carries on from where the selection now is, so that stepping to the + // next match goes to the one after it rather than the one after the match the + // user last stepped to. + view.SetNearestSearchPosition() +} + +// SelectChangeBlock selects the whole change block around the given change line, for +// hunk mode: the cursor goes to the block's first line and the range anchor to its +// last, so the native range highlight spans the block. With no block to be found — +// a diff with no changes in it — it falls back to a single-line selection. +// +// scrollIntoView brings the block's first line on screen, for the commands that mean +// to go there; a click leaves it false, so that the view doesn't move under the mouse +// when the block the click landed in starts above the viewport. +func (self *DiffLineHelper) SelectChangeBlock( + pane types.DiffPaneContext, changeViewLine int, scrollIntoView bool, +) { + view := pane.GetView() + start, end, ok := self.ChangeBlockBounds(view, changeViewLine) + if !ok { + pane.DiffSelectState().Mode = types.DiffSelectModeLine + view.CancelRangeSelect() + self.ShowSelectionAtLine(view, changeViewLine, scrollIntoView) + return + } + view.SetRangeSelectStart(end) + self.ShowSelectionAtLine(view, start, scrollIntoView) +} + +// SelectedHunkBounds returns the change block selected in hunk mode. The range +// anchor stays on the block's far end when a click moves the cursor before its +// handler runs, so it still identifies the selected block. +func (self *DiffLineHelper) SelectedHunkBounds(view *gocui.View) (int, int, bool) { + anchor := view.RangeSelectStartY() + if anchor < 0 { + return 0, 0, false + } + return self.ChangeBlockBounds(view, anchor) +} diff --git a/pkg/gui/controllers/main_view_controller.go b/pkg/gui/controllers/main_view_controller.go index f8fcaa4da..71561043c 100644 --- a/pkg/gui/controllers/main_view_controller.go +++ b/pkg/gui/controllers/main_view_controller.go @@ -207,7 +207,7 @@ func (self *MainViewController) togglePanel() error { isDiff := self.isDiffView() self.c.Context().Push(self.otherContext, types.OnFocusOpts{}) if isDiff { - establishDiffSelection(self.c, self.otherContext, -1) + self.c.Helpers().DiffLine.EstablishSelection(self.otherContext, -1) } return nil } @@ -322,11 +322,11 @@ func revealSelectionAfterAction(c *ControllerCommon, pane types.DiffPaneContext, c.Helpers().DiffLine.RevealChangeLineAtOrdinal(view, ordinal, func(viewLine int) { if selectHunk { - selectDiffHunk(c, pane, viewLine, true) + c.Helpers().DiffLine.SelectChangeBlock(pane, viewLine, true) return } view.CancelRangeSelect() - showSelectionAtLine(view, viewLine, true) + c.Helpers().DiffLine.ShowSelectionAtLine(view, viewLine, true) }) } @@ -539,7 +539,7 @@ func (self *MainViewController) selectClickedDiffLine(viewLine int) { if start, end, ok := self.c.Helpers().DiffLine.SelectedHunkBounds(view); ok && viewLine >= start && viewLine <= end { self.context.ResetDiffSelectMode() - showSelectionAtLine(view, viewLine, false) + self.c.Helpers().DiffLine.ShowSelectionAtLine(view, viewLine, false) return } if self.c.Helpers().DiffLine.IsChangeLine(view, viewLine) { @@ -548,122 +548,11 @@ func (self *MainViewController) selectClickedDiffLine(viewLine int) { } } self.context.ResetDiffSelectMode() - showSelectionAtLine(view, viewLine, false) -} - -// establishDiffSelection turns on the focused main view's selection once the view has -// been focused. clickedViewLine is the view line a click pointed at, or -1 for -// keyboard focus, which points at no particular line and so starts at the first -// change line on screen. -// -// Focusing never moves the view: you focus the diff you are reading in order to point -// at something in it, so the selection goes where you are looking rather than the -// view going where the selection would like to be. With no change line on screen at -// all — a long stretch of context — it lands on the middle visible line, the likeliest -// one to be the one being read. -// -// With hunk mode configured as the default the selection widens to the whole change -// block: keyboard focus lands on the first block on screen, and a click on a change -// line selects that line's block, ready to act on. A click on context still selects -// just that line — the click points at it precisely, so it stays editable. -func establishDiffSelection(c *ControllerCommon, mainContext *context.MainContext, clickedViewLine int) { - mainContext.ResetDiffSelectMode() - view := mainContext.GetView() - - // The panel beneath renders a diff, but that diff may hold nothing to act on: a - // binary file, or an empty commit. Rendering it worked that out, so the pane is - // already showing no selection and there is nowhere to put one. - if !c.Helpers().DiffLine.ViewHasChangeLines(view) { - return - } - - if clickedViewLine >= 0 { - // Remember where the click landed so that a drag that follows anchors its range - // there, even when this click selects a whole hunk. - mainContext.SetDragAnchorViewLine(clickedViewLine) - if hunkModeApplies(c, view, clickedViewLine) && - c.Helpers().DiffLine.IsChangeLine(view, clickedViewLine) { - mainContext.DiffSelectState().Mode = types.DiffSelectModeHunk - selectDiffHunk(c, mainContext, clickedViewLine, false) - return - } - showSelectionAtLine(view, clickedViewLine, false) - return - } - - target, ok := changeToSelectOnScreen(c, view) - if !ok { - showSelectionAtLine(view, view.MiddleVisibleLineIdx(), false) - return - } - if hunkModeApplies(c, view, target) { - mainContext.DiffSelectState().Mode = types.DiffSelectModeHunk - selectDiffHunk(c, mainContext, target, false) - return - } - showSelectionAtLine(view, target, false) -} - -// changeToSelectOnScreen returns the change line keyboard focus establishes the -// selection on. In hunk mode that is the first block that begins on screen, so that -// the block being offered up is one the user can see the extent of, falling back to a -// block that reaches into the view from above — a change longer than the screen, where -// there is nothing else to offer. Line by line it is simply the first change line on -// screen. ok is false when the viewport shows no change at all. -func changeToSelectOnScreen(c *ControllerCommon, view *gocui.View) (int, bool) { - if c.UserConfig().Gui.UseHunkModeInStagingView { - return c.Helpers().DiffLine.FirstChangeBlockInView(view) - } - return c.Helpers().DiffLine.FirstChangeLineInView(view) -} - -// hunkModeApplies reports whether an established selection should start out as the -// whole change block around the given change line. That's what the config asks for, -// except over a file shown as one solid block of changes, where it would select the -// whole file — see DiffLineHelper.IsSingleHunkForWholeFile. -func hunkModeApplies(c *ControllerCommon, view *gocui.View, changeViewLine int) bool { - return c.UserConfig().Gui.UseHunkModeInStagingView && - !c.Helpers().DiffLine.IsSingleHunkForWholeFile(view, changeViewLine) -} - -// showSelectionAtLine moves the focused main view's selection to the given view line, -// clamped to the content. scrollIntoView scrolls the line into view when it's -// off-screen, for navigating to it; a click leaves it false, the clicked line being on -// screen already. -func showSelectionAtLine(view *gocui.View, lineIdx int, scrollIntoView bool) { - view.FocusPoint(0, lo.Clamp(lineIdx, 0, max(0, view.ViewLinesHeight()-1)), scrollIntoView) - - // A search carries on from where the selection now is, so that stepping to the - // next match goes to the one after it rather than the one after the match the - // user last stepped to. - view.SetNearestSearchPosition() + self.c.Helpers().DiffLine.ShowSelectionAtLine(view, viewLine, false) } func (self *MainViewController) selectHunkAround(changeViewLine int, scrollIntoView bool) { - selectDiffHunk(self.c, self.context, changeViewLine, scrollIntoView) -} - -// selectDiffHunk selects the whole change block around the given change line, for -// hunk mode: the cursor goes to the block's first line and the range anchor to its -// last, so the native range highlight spans the block. With no block to be found — -// a diff with no changes in it — it falls back to a single-line selection. -// -// scrollIntoView brings the block's first line on screen, for the commands that mean -// to go there; a click leaves it false, so that the view doesn't move under the mouse -// when the block the click landed in starts above the viewport. -func selectDiffHunk( - c *ControllerCommon, pane types.DiffPaneContext, changeViewLine int, scrollIntoView bool, -) { - view := pane.GetView() - start, end, ok := c.Helpers().DiffLine.ChangeBlockBounds(view, changeViewLine) - if !ok { - pane.DiffSelectState().Mode = types.DiffSelectModeLine - view.CancelRangeSelect() - showSelectionAtLine(view, changeViewLine, scrollIntoView) - return - } - view.SetRangeSelectStart(end) - showSelectionAtLine(view, start, scrollIntoView) + self.c.Helpers().DiffLine.SelectChangeBlock(self.context, changeViewLine, scrollIntoView) } // navigate moves the focused main view to the row find locates from the current @@ -762,7 +651,7 @@ func (self *MainViewController) placeNavigationTarget(target int, alignTop bool) } // Line mode leaves a single-line selection at the target; an active range extends // to it, the anchor being untouched. - showSelectionAtLine(v, target, true) + self.c.Helpers().DiffLine.ShowSelectionAtLine(v, target, true) } // scrollTargetToTop scrolls the given row of the diff to the top of the view, leaving @@ -794,7 +683,7 @@ func (self *MainViewController) moveCursor(delta int) { } else if delta == 1 { checkScrollDown(self.context.GetViewTrait(), self.c.UserConfig(), before, after) } - showSelectionAtLine(v, after, true) + self.c.Helpers().DiffLine.ShowSelectionAtLine(v, after, true) } // collapseForLineMove drops hunk mode, and a non-sticky range, back to a single-line @@ -841,7 +730,7 @@ func (self *MainViewController) adjustSelection(delta int) { // of the diff — dropping hunk mode and a non-sticky range like a plain move does. func (self *MainViewController) selectAbsoluteLine(target int) { self.collapseForLineMove() - showSelectionAtLine(self.context.GetView(), target, true) + self.c.Helpers().DiffLine.ShowSelectionAtLine(self.context.GetView(), target, true) } // selectingRange reports whether a range selection is currently active: we're in diff --git a/pkg/gui/controllers/switch_to_focused_main_view_controller.go b/pkg/gui/controllers/switch_to_focused_main_view_controller.go index e179b3a66..189d3c6ac 100644 --- a/pkg/gui/controllers/switch_to_focused_main_view_controller.go +++ b/pkg/gui/controllers/switch_to_focused_main_view_controller.go @@ -84,7 +84,7 @@ func (self *SwitchToFocusedMainViewController) focusMainView(mainViewContext *co self.c.Context().Push(mainViewContext, types.OnFocusOpts{}) if _, ok := self.context.(types.DiffMainViewContext); ok { - establishDiffSelection(self.c, mainViewContext, clickedLineIdx) + self.c.Helpers().DiffLine.EstablishSelection(mainViewContext, clickedLineIdx) } return nil From 7d327339afb3877d7209b58bf2e900bf2120bc92 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 18 Aug 2026 18:53:06 +0200 Subject: [PATCH 07/21] Follow the focus into the pane that is left MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each side of a file's diff has a pane of its own, and a pane is only shown while its side has something in it. So anything that empties the side the focus is on takes that pane away with it: committing what was staged, or a commit or a discard happening outside lazygit and arriving with a refresh. The focus was left on a pane that isn't there any more, where the next keypress acted on nothing. The render is what decides which panes are shown, so the question is asked there, of every render rather than of the handful of actions that could think to ask it themselves. The pane the focus moves into gets its selection once that render has finished and there is something to put one on, the way focusing it by hand would — and shows none until then, so that the selection it was left with the last time it was used doesn't appear for a frame. Co-authored-by: Claude Opus 5 (1M context) --- pkg/gui/main_panels.go | 72 +++++++++++++++++- ...cus_follows_a_pane_emptied_from_outside.go | 52 +++++++++++++ .../focus_follows_into_a_pane_taking_over.go | 74 +++++++++++++++++++ pkg/integration/tests/test_list.go | 2 + pkg/tasks/tasks.go | 36 +++++---- pkg/tasks/tasks_test.go | 9 ++- 6 files changed, 228 insertions(+), 17 deletions(-) create mode 100644 pkg/integration/tests/main_view/focus_follows_a_pane_emptied_from_outside.go create mode 100644 pkg/integration/tests/main_view/focus_follows_into_a_pane_taking_over.go diff --git a/pkg/gui/main_panels.go b/pkg/gui/main_panels.go index 8feeaccf6..5613525d0 100644 --- a/pkg/gui/main_panels.go +++ b/pkg/gui/main_panels.go @@ -4,6 +4,7 @@ import ( "github.com/jesseduffield/lazygit/pkg/gocui" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/types" + "github.com/jesseduffield/lazygit/pkg/tasks" ) func (gui *Gui) runTaskForView(view *gocui.View, task types.UpdateTask) error { @@ -108,9 +109,14 @@ func (gui *Gui) allMainContextPairs() []types.MainContextPair { } func (gui *Gui) refreshMainViews(opts types.RefreshMainOpts) { + panes := mainPanesFor(opts) + + // Before the render is triggered, so that the pane the focus moves into can be + // told where to put its selection as it renders. + gui.followFocusIntoShownPane(opts.Pair, panes) + gui.moveMainContextPairToTop(opts.Pair) - panes := mainPanesFor(opts) gui.handOverMainSection(opts.Pair, panes) if opts.Main != nil { @@ -185,6 +191,70 @@ func mainPanesFor(opts types.RefreshMainOpts) types.MainPanes { } } +// followFocusIntoShownPane moves the focus out of a main pane that the render about to +// happen leaves nothing in, and into the one it does. +// +// Each side of a file's diff has a pane of its own, and a pane is only shown while its +// side has something in it. So anything that empties the side the focus is on takes +// that pane away with it: staging the last unstaged change, committing what was +// staged, or either of those happening outside lazygit and arriving with a refresh. +// Left where it was, the focus would be on a pane that isn't there, and the next +// keypress would act on nothing. +// +// The pane moved into gets its selection once the render has finished and there is +// something to put one on, and shows none until then, so that the selection it was +// left with the last time it was used doesn't appear for a frame. A pane that has +// already been told where to put its selection — by the action that caused all this — +// keeps what it was told. +func (gui *Gui) followFocusIntoShownPane(pair types.MainContextPair, panes types.MainPanes) { + // The focused main view's two panes only: the staging and patch-building views + // arrange theirs for themselves, and the merge-conflicts view has just the one. + if pair.Main.GetKey() != context.NORMAL_MAIN_CONTEXT_KEY { + return + } + + current := gui.State.ContextMgr.CurrentStatic().GetKey() + if current != pair.Main.GetKey() && current != pair.Secondary.GetKey() { + return + } + shown := onlyShownPane(pair, panes) + if shown == nil || shown.GetKey() == current { + return + } + + target := gui.mainContextForView(shown.GetView()) + target.SetHasSelectableContent(false) + gui.State.ContextMgr.UpdateSelectionHighlights() + if manager := gui.getManager(target.GetView()); !manager.HasRestoreForNextTask() { + manager.SetRestoreForNextTask(&tasks.RenderRestore{ + // The whole render is read before it is shown: where the selection goes + // is decided from what is there, and a change line further down would + // otherwise be missed. + FirstPaintReady: func() bool { return false }, + Apply: func(swapIn func()) bool { + swapIn() + gui.helpers.DiffLine.EstablishSelection(target, -1) + return false + }, + }) + } + gui.State.ContextMgr.Push(target, types.OnFocusOpts{}) +} + +// onlyShownPane returns the main pane a render leaves showing on its own, or nil when +// it leaves both showing. +func onlyShownPane(pair types.MainContextPair, panes types.MainPanes) types.Context { + switch panes { + case types.MainPaneOnly: + return pair.Main + case types.SecondaryPaneOnly: + return pair.Secondary + case types.BothMainPanes: + return nil + } + return nil +} + // clampDiffSelectionToContent brings the focused main view's selection back onto the // content when the render that just finished left the diff with fewer lines than the // selection was on — a diff renderer that renders the same diff more compactly, a diff --git a/pkg/integration/tests/main_view/focus_follows_a_pane_emptied_from_outside.go b/pkg/integration/tests/main_view/focus_follows_a_pane_emptied_from_outside.go new file mode 100644 index 000000000..708e0d2f0 --- /dev/null +++ b/pkg/integration/tests/main_view/focus_follows_a_pane_emptied_from_outside.go @@ -0,0 +1,52 @@ +package main_view + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var FocusFollowsAPaneEmptiedFromOutside = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Committing the staged changes outside lazygit takes the staged pane away, so the focus follows into the one that is left", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInStagingView = false + }, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("file1", "one\ntwo\nthree\nfour\nfive\n") + shell.Commit("one") + + // One change on each side, so the diff is split. + shell.UpdateFileAndAdd("file1", "one\nSTAGED\ntwo\nthree\nfour\nfive\n") + shell.UpdateFile("file1", "one\nSTAGED\ntwo\nthree\nUNSTAGED\nfour\nfive\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Files(). + IsFocused(). + Press(keys.Universal.FocusMainView) + + t.Views().Main(). + IsFocused(). + Press(keys.Universal.TogglePanel) + + t.Views().Secondary(). + IsFocused(). + Title(Equals("Staged changes")). + SelectedLines( + Contains("+STAGED"), + ) + + // Nothing lazygit did empties the staged side here; the refresh simply finds + // it empty, and the pane the focus was in is gone by the time it lands. + t.Shell().Commit("two") + t.GlobalPress(keys.Universal.Refresh) + + t.Views().Secondary().IsInvisible() + t.Views().Main(). + IsFocused(). + Title(Equals("Unstaged changes")). + SelectedLines( + Contains("+UNSTAGED"), + ) + }, +}) diff --git a/pkg/integration/tests/main_view/focus_follows_into_a_pane_taking_over.go b/pkg/integration/tests/main_view/focus_follows_into_a_pane_taking_over.go new file mode 100644 index 000000000..0f2a9af0d --- /dev/null +++ b/pkg/integration/tests/main_view/focus_follows_into_a_pane_taking_over.go @@ -0,0 +1,74 @@ +package main_view + +import ( + "fmt" + "strings" + + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var FocusFollowsIntoAPaneTakingOver = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "The pane the focus follows into as it takes the section over gets its selection from the top of the diff it is given", + ExtraCmdArgs: []string{}, + Skip: false, + Width: 120, + Height: 30, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInStagingView = false + }, + SetupRepo: func(shell *Shell) { + lines := make([]string, 40) + for i := range lines { + lines[i] = fmt.Sprintf("line%02d", i+1) + } + shell.CreateFileAndAdd("file1", strings.Join(lines, "\n")+"\n") + shell.Commit("one") + + // Everything staged and nothing unstaged, so the staged side has the section to + // itself, with more changes in it than fit. + for i := range lines { + lines[i] = strings.ToUpper(lines[i]) + } + shell.UpdateFileAndAdd("file1", strings.Join(lines, "\n")+"\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Files(). + IsFocused(). + Lines( + Contains("M file1").IsSelected(), + ) + + // Read a way into the diff before focusing it, so that the selection starts out + // somewhere other than the first change. + t.Views().Secondary(). + IsVisible(). + ScrollWheelDown(). + ScrollWheelDown(). + ScrollWheelDown(). + ScrollWheelDown(). + OriginY(8) + + t.Views().Files().Press(keys.Universal.FocusMainView) + t.Views().Secondary(). + IsFocused(). + SelectedLines( + Contains("-line04"), + ) + + // The index is reset outside lazygit, so the staged side empties and the + // unstaged side has everything: the pane the focus is in goes away and the other + // one takes the section over with a diff that is new to it. + t.Shell().RunCommand([]string{"git", "reset"}) + t.GlobalPress(keys.Universal.Refresh) + + t.Views().Secondary().IsInvisible() + t.Views().Main(). + IsFocused(). + Title(Equals("Unstaged changes")). + OriginY(0). + SelectedLines( + Contains("-line01"), + ) + }, +}) diff --git a/pkg/integration/tests/test_list.go b/pkg/integration/tests/test_list.go index cc6572f2e..fb58456b9 100644 --- a/pkg/integration/tests/test_list.go +++ b/pkg/integration/tests/test_list.go @@ -375,6 +375,8 @@ var tests = []*components.IntegrationTest{ main_view.EditSelectedDiffLine, main_view.EscapeDismissesSelection, main_view.FileNavigationScrollsToTheTop, + main_view.FocusFollowsAPaneEmptiedFromOutside, + main_view.FocusFollowsIntoAPaneTakingOver, main_view.HideSelectionWhenChangesVanish, main_view.KeepAWrappedLineCoveredAcrossARerender, main_view.KeepBothHalvesOfAChangeSelected, diff --git a/pkg/tasks/tasks.go b/pkg/tasks/tasks.go index cbabc868f..2282906b4 100644 --- a/pkg/tasks/tasks.go +++ b/pkg/tasks/tasks.go @@ -207,6 +207,16 @@ func (self *ViewBufferManager) SetRestoreForNextTask(restore *RenderRestore) { self.restoreForNextTask = restore } +// HasRestoreForNextTask reports whether the next command task already has a position +// waiting to be put back, for a caller that would otherwise install one of its own +// over it. +func (self *ViewBufferManager) HasRestoreForNextTask() bool { + self.taskIDMutex.Lock() + defer self.taskIDMutex.Unlock() + + return self.restoreForNextTask != nil +} + func (self *ViewBufferManager) getRestoreForNextTask() *RenderRestore { self.taskIDMutex.Lock() defer self.taskIDMutex.Unlock() @@ -543,22 +553,22 @@ func (self *ViewBufferManager) NewCmdTask(start func() (Cmd, io.Reader), prefix return } painted = true - if restore != nil { - // The restore does the swap itself, so that it can find where the - // user was in the new content before it is revealed. - placed := restore.Apply(self.swapInRender) - self.clearRestore(restore) - if placed { - // The view is where the user left it, which is exactly what the - // scroll reset would undo. - self.newContentPending.Store(false) - return - } - } - self.swapInRender() + // Content the view hasn't seen is shown from the top, and this is where + // the view goes there — before the restore below, which decides where to + // put the view from where it is. The position the paint settles on is the + // restore's to move from, so it has to be the one the new content is + // about to be revealed at. if self.newContentPending.Swap(false) { self.resetOrigin() } + if restore != nil { + // The restore does the swap itself, so that it can find where the + // user was in the new content before it is revealed. + restore.Apply(self.swapInRender) + self.clearRestore(restore) + return + } + self.swapInRender() } // Set LAZYGIT_SLOW_RENDER= to sleep that long after each diff --git a/pkg/tasks/tasks_test.go b/pkg/tasks/tasks_test.go index 31c9a09d3..187b9aed1 100644 --- a/pkg/tasks/tasks_test.go +++ b/pkg/tasks/tasks_test.go @@ -388,8 +388,8 @@ func TestLoadingIndicatorOnlyTakesOverForNewContent(t *testing.T) { // A pending restore takes the first paint over: it says when enough of the new // content has arrived to show the position it remembers, and does the swap itself so // that it can look for that position while the previous content is still displayed. -// Having put the view where the user left it, it also keeps the scroll reset that new -// content would otherwise get. +// The scroll reset that new content is owed happens before it runs, so that where it +// puts the view is where the view stays. func TestNewCmdTaskRestore(t *testing.T) { writer := bytes.NewBuffer(nil) linesWritten := func() int { return strings.Count(writer.String(), "\n") } @@ -400,6 +400,7 @@ func TestNewCmdTaskRestore(t *testing.T) { applyAtLines := -1 swappedBeforeApply := false swappedByApply := false + resetsBeforeApply := -1 manager := NewViewBufferManager( utils.NewDummyLog(), @@ -422,6 +423,7 @@ func TestNewCmdTaskRestore(t *testing.T) { applyCount++ applyAtLines = linesWritten() swappedBeforeApply = swappedBeforeApply || swapped + resetsBeforeApply = getResetOriginCallCount() swapIn() swappedByApply = swapped return true @@ -443,7 +445,8 @@ func TestNewCmdTaskRestore(t *testing.T) { // fill the view. assert.GreaterOrEqual(t, applyAtLines, 5) assert.Less(t, applyAtLines, 30) - assert.Equal(t, 0, getResetOriginCallCount(), "a restore that placed the view leaves the scroll alone") + assert.Equal(t, 1, resetsBeforeApply, "new content should be put at the top before the restore places it") + assert.Equal(t, 1, getResetOriginCallCount(), "and not reset again afterwards, over the restore") } // A restore that never finds what it is looking for keeps the task reading to the From 96c961ebd2232eaf8fbd16a22b33195b87499c5b Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 19 Aug 2026 11:21:35 +0200 Subject: [PATCH 08/21] Stop a render restore saying whether it placed the view Nothing has read that since the paint started settling the scroll position before consulting the restore: what the answer was for was deciding whether the reset the new content was owed still had to happen, and by then it has. Co-authored-by: Claude Opus 5 (1M context) --- pkg/gui/controllers/helpers/diff_line_restore.go | 11 ++++------- pkg/gui/main_panels.go | 3 +-- pkg/tasks/tasks.go | 8 ++++---- pkg/tasks/tasks_test.go | 9 +++------ 4 files changed, 12 insertions(+), 19 deletions(-) diff --git a/pkg/gui/controllers/helpers/diff_line_restore.go b/pkg/gui/controllers/helpers/diff_line_restore.go index 24843a396..35a2e4337 100644 --- a/pkg/gui/controllers/helpers/diff_line_restore.go +++ b/pkg/gui/controllers/helpers/diff_line_restore.go @@ -370,7 +370,7 @@ func (self *DiffLineHelper) installDiffLineRestore( // revealed with it stranded at the bottom of a half-filled view. return view.OffscreenLineCount() >= foundLine+viewHeight }, - Apply: func(swapIn func()) bool { + Apply: func(swapIn func()) { bufferLine := foundLine if bufferLine == -1 { if line, ok := findComplete(view.OffscreenDiffLineContents()); ok { @@ -381,14 +381,11 @@ func (self *DiffLineHelper) installDiffLineRestore( swapIn() if bufferLine == -1 { - return false + return } - viewLine, ok := view.ViewLineForBufferLine(bufferLine) - if !ok { - return false + if viewLine, ok := view.ViewLineForBufferLine(bufferLine); ok { + place(viewLine) } - place(viewLine) - return true }, }) } diff --git a/pkg/gui/main_panels.go b/pkg/gui/main_panels.go index 5613525d0..637181f4a 100644 --- a/pkg/gui/main_panels.go +++ b/pkg/gui/main_panels.go @@ -231,10 +231,9 @@ func (gui *Gui) followFocusIntoShownPane(pair types.MainContextPair, panes types // is decided from what is there, and a change line further down would // otherwise be missed. FirstPaintReady: func() bool { return false }, - Apply: func(swapIn func()) bool { + Apply: func(swapIn func()) { swapIn() gui.helpers.DiffLine.EstablishSelection(target, -1) - return false }, }) } diff --git a/pkg/tasks/tasks.go b/pkg/tasks/tasks.go index 2282906b4..dbc83758a 100644 --- a/pkg/tasks/tasks.go +++ b/pkg/tasks/tasks.go @@ -191,10 +191,10 @@ type RenderRestore struct { // while the previous content is still displayed, and the new content is never // drawn at the previous render's scroll position. // - // It must call swapIn either way, and reports whether it placed the view: when - // it didn't, because what it was looking for is not in the new content, the - // task does what it would have done without a restore. - Apply func(swapIn func()) bool + // It must call swapIn even when it finds nothing to place the view on, in which + // case the view keeps the position the paint gave it: the offset it had, or the + // top for content the view hasn't seen. + Apply func(swapIn func()) } // SetRestoreForNextTask arranges for the next command task to put the view back diff --git a/pkg/tasks/tasks_test.go b/pkg/tasks/tasks_test.go index 187b9aed1..7383070e7 100644 --- a/pkg/tasks/tasks_test.go +++ b/pkg/tasks/tasks_test.go @@ -419,14 +419,13 @@ func TestNewCmdTaskRestore(t *testing.T) { manager.SetRestoreForNextTask(&RenderRestore{ // Ready once five lines have loaded — well before the view is filled (30). FirstPaintReady: func() bool { return linesWritten() >= 5 }, - Apply: func(swapIn func()) bool { + Apply: func(swapIn func()) { applyCount++ applyAtLines = linesWritten() swappedBeforeApply = swappedBeforeApply || swapped resetsBeforeApply = getResetOriginCallCount() swapIn() swappedByApply = swapped - return true }, }) @@ -477,10 +476,9 @@ func TestNewCmdTaskRestoreThatFindsNothing(t *testing.T) { manager.SetRestoreForNextTask(&RenderRestore{ FirstPaintReady: func() bool { return false }, - Apply: func(swapIn func()) bool { + Apply: func(swapIn func()) { applyCount++ swapIn() - return false }, }) @@ -520,10 +518,9 @@ func TestRestoreSurvivesTaskReplacement(t *testing.T) { manager.SetRestoreForNextTask(&RenderRestore{ FirstPaintReady: func() bool { return false }, - Apply: func(swapIn func()) bool { + Apply: func(swapIn func()) { applyCount.Add(1) swapIn() - return true }, }) From 0baa1ec8d01cdc1faf123803be35ffcf5227c1f9 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 18 Aug 2026 18:56:42 +0200 Subject: [PATCH 09/21] Leave a pane that only the permanent split keeps around MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Configured to always split the diff, a pane is shown whether or not its side of the file holds anything, so emptying the side the focus is on no longer takes the pane away — but it does take away everything there was to do there, which is the question the focus is really asking. So the render says which of the panes it is giving something to act on, rather than the focus reading that off which panes are shown. Co-authored-by: Claude Opus 5 (1M context) --- pkg/gui/controllers/files_controller.go | 14 ++--- pkg/gui/main_panels.go | 50 ++++++++--------- pkg/gui/types/rendering.go | 5 ++ ...focus_leaves_an_always_split_empty_pane.go | 53 +++++++++++++++++++ pkg/integration/tests/test_list.go | 1 + 5 files changed, 93 insertions(+), 30 deletions(-) create mode 100644 pkg/integration/tests/main_view/focus_leaves_an_always_split_empty_pane.go diff --git a/pkg/gui/controllers/files_controller.go b/pkg/gui/controllers/files_controller.go index ab58de7c8..93bc6f379 100644 --- a/pkg/gui/controllers/files_controller.go +++ b/pkg/gui/controllers/files_controller.go @@ -386,18 +386,20 @@ func (self *FilesController) renderWorkingTreeDiff(node *filetree.FileNode) { if showUnstaged { cmdObj := self.c.Git().WorkingTree.WorktreeFileDiffCmdObj(node, false, false, paths) refreshOpts.Main = &types.ViewUpdateOpts{ - Task: types.NewRunDiffRendererTask(cmdObj.GetCmd()), - SubTitle: self.c.Helpers().Diff.IgnoringWhitespaceSubTitle(), - Title: self.c.Tr.UnstagedChanges, + Task: types.NewRunDiffRendererTask(cmdObj.GetCmd()), + SubTitle: self.c.Helpers().Diff.IgnoringWhitespaceSubTitle(), + Title: self.c.Tr.UnstagedChanges, + NothingToActOn: !node.GetHasUnstagedChanges(), } } if showStaged { cmdObj := self.c.Git().WorkingTree.WorktreeFileDiffCmdObj(node, false, true, paths) refreshOpts.Secondary = &types.ViewUpdateOpts{ - Task: types.NewRunDiffRendererTask(cmdObj.GetCmd()), - SubTitle: self.c.Helpers().Diff.IgnoringWhitespaceSubTitle(), - Title: self.c.Tr.StagedChanges, + Task: types.NewRunDiffRendererTask(cmdObj.GetCmd()), + SubTitle: self.c.Helpers().Diff.IgnoringWhitespaceSubTitle(), + Title: self.c.Tr.StagedChanges, + NothingToActOn: !node.GetHasStagedChanges(), } } diff --git a/pkg/gui/main_panels.go b/pkg/gui/main_panels.go index 637181f4a..ba8e7c200 100644 --- a/pkg/gui/main_panels.go +++ b/pkg/gui/main_panels.go @@ -113,7 +113,7 @@ func (gui *Gui) refreshMainViews(opts types.RefreshMainOpts) { // Before the render is triggered, so that the pane the focus moves into can be // told where to put its selection as it renders. - gui.followFocusIntoShownPane(opts.Pair, panes) + gui.followFocusIntoWorkablePane(opts) gui.moveMainContextPairToTop(opts.Pair) @@ -191,38 +191,38 @@ func mainPanesFor(opts types.RefreshMainOpts) types.MainPanes { } } -// followFocusIntoShownPane moves the focus out of a main pane that the render about to -// happen leaves nothing in, and into the one it does. +// followFocusIntoWorkablePane moves the focus out of a main pane that the render about +// to happen leaves nothing to work on, and into the one it does. // -// Each side of a file's diff has a pane of its own, and a pane is only shown while its -// side has something in it. So anything that empties the side the focus is on takes -// that pane away with it: staging the last unstaged change, committing what was +// Each side of a file's diff has a pane of its own, and a pane holds something only +// while its side of the file does. So anything that empties the side the focus is on +// leaves that pane with nothing: staging the last unstaged change, committing what was // staged, or either of those happening outside lazygit and arriving with a refresh. -// Left where it was, the focus would be on a pane that isn't there, and the next -// keypress would act on nothing. +// Usually the pane goes away with its content; configured to always split the diff it +// stays, empty. Either way the focus has nothing left to act on where it is. // // The pane moved into gets its selection once the render has finished and there is // something to put one on, and shows none until then, so that the selection it was // left with the last time it was used doesn't appear for a frame. A pane that has // already been told where to put its selection — by the action that caused all this — // keeps what it was told. -func (gui *Gui) followFocusIntoShownPane(pair types.MainContextPair, panes types.MainPanes) { +func (gui *Gui) followFocusIntoWorkablePane(opts types.RefreshMainOpts) { // The focused main view's two panes only: the staging and patch-building views // arrange theirs for themselves, and the merge-conflicts view has just the one. - if pair.Main.GetKey() != context.NORMAL_MAIN_CONTEXT_KEY { + if opts.Pair.Main.GetKey() != context.NORMAL_MAIN_CONTEXT_KEY { return } current := gui.State.ContextMgr.CurrentStatic().GetKey() - if current != pair.Main.GetKey() && current != pair.Secondary.GetKey() { + if current != opts.Pair.Main.GetKey() && current != opts.Pair.Secondary.GetKey() { return } - shown := onlyShownPane(pair, panes) - if shown == nil || shown.GetKey() == current { + pane := onlyWorkablePane(opts) + if pane == nil || pane.GetKey() == current { return } - target := gui.mainContextForView(shown.GetView()) + target := gui.mainContextForView(pane.GetView()) target.SetHasSelectableContent(false) gui.State.ContextMgr.UpdateSelectionHighlights() if manager := gui.getManager(target.GetView()); !manager.HasRestoreForNextTask() { @@ -240,18 +240,20 @@ func (gui *Gui) followFocusIntoShownPane(pair types.MainContextPair, panes types gui.State.ContextMgr.Push(target, types.OnFocusOpts{}) } -// onlyShownPane returns the main pane a render leaves showing on its own, or nil when -// it leaves both showing. -func onlyShownPane(pair types.MainContextPair, panes types.MainPanes) types.Context { - switch panes { - case types.MainPaneOnly: - return pair.Main - case types.SecondaryPaneOnly: - return pair.Secondary - case types.BothMainPanes: +// onlyWorkablePane returns the main pane a render leaves as the only one worth having +// the focus in, or nil when that is true of both of them or of neither. Being shown is +// not the same as being worth working in: a pane the layout keeps around for the sake +// of always splitting the diff shows an empty side of the file. +func onlyWorkablePane(opts types.RefreshMainOpts) types.Context { + main := opts.Main != nil && !opts.Main.NothingToActOn + secondary := opts.Secondary != nil && !opts.Secondary.NothingToActOn + if main == secondary { return nil } - return nil + if main { + return opts.Pair.Main + } + return opts.Pair.Secondary } // clampDiffSelectionToContent brings the focused main view's selection back onto the diff --git a/pkg/gui/types/rendering.go b/pkg/gui/types/rendering.go index f59a535ba..f88a207b6 100644 --- a/pkg/gui/types/rendering.go +++ b/pkg/gui/types/rendering.go @@ -38,6 +38,11 @@ type ViewUpdateOpts struct { SubTitle string Task UpdateTask + + // NothingToActOn marks a pane that is being shown only because the layout is + // configured to always split the diff: its side of the file holds nothing, so it + // is not a pane to leave the focus in. + NothingToActOn bool } type RefreshMainOpts struct { diff --git a/pkg/integration/tests/main_view/focus_leaves_an_always_split_empty_pane.go b/pkg/integration/tests/main_view/focus_leaves_an_always_split_empty_pane.go new file mode 100644 index 000000000..a49330e71 --- /dev/null +++ b/pkg/integration/tests/main_view/focus_leaves_an_always_split_empty_pane.go @@ -0,0 +1,53 @@ +package main_view + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var FocusLeavesAnAlwaysSplitEmptyPane = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Configured to always split the diff, the emptied pane stays but the focus still leaves it", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInStagingView = false + cfg.GetUserConfig().Gui.SplitDiff = "always" + }, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("file1", "one\ntwo\nthree\nfour\nfive\n") + shell.Commit("one") + + shell.UpdateFileAndAdd("file1", "one\nSTAGED\ntwo\nthree\nfour\nfive\n") + shell.UpdateFile("file1", "one\nSTAGED\ntwo\nthree\nUNSTAGED\nfour\nfive\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Files(). + IsFocused(). + Press(keys.Universal.FocusMainView) + + t.Views().Main(). + IsFocused(). + Press(keys.Universal.TogglePanel) + + t.Views().Secondary(). + IsFocused(). + SelectedLines( + Contains("+STAGED"), + ) + + t.Shell().Commit("two") + t.GlobalPress(keys.Universal.Refresh) + + // The staged side is empty now, but its pane is still shown because the split + // is configured as permanent. There is nothing left to act on in it, so the + // focus goes where there is. + t.Views().Secondary(). + IsVisible(). + Content(DoesNotContain("STAGED")) + t.Views().Main(). + IsFocused(). + SelectedLines( + Contains("+UNSTAGED"), + ) + }, +}) diff --git a/pkg/integration/tests/test_list.go b/pkg/integration/tests/test_list.go index fb58456b9..bcdf37e43 100644 --- a/pkg/integration/tests/test_list.go +++ b/pkg/integration/tests/test_list.go @@ -377,6 +377,7 @@ var tests = []*components.IntegrationTest{ main_view.FileNavigationScrollsToTheTop, main_view.FocusFollowsAPaneEmptiedFromOutside, main_view.FocusFollowsIntoAPaneTakingOver, + main_view.FocusLeavesAnAlwaysSplitEmptyPane, main_view.HideSelectionWhenChangesVanish, main_view.KeepAWrappedLineCoveredAcrossARerender, main_view.KeepBothHalvesOfAChangeSelected, From 71cc0680f1a086a725f15695fee7b59cfa862157 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Sun, 16 Aug 2026 14:21:36 +0200 Subject: [PATCH 10/21] Carry the acted-on lines into the pane the work lands in MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each side of a file's diff has a pane of its own, but a pane is only shown while its side has something in it: staging the last unstaged change takes the upper pane away, and unstaging the last staged one takes the lower one away. The focus follows into the pane that is left, and the selection has to be waiting there when it arrives — on the lines just acted on, which is where they are now, unless they were discarded rather than moved, in which case on what is left of the file. The pane being moved to shows no selection until the restore places one, so that the selection it was left with the last time it was used doesn't appear for a frame. Whether the acted-on side still holds anything is a question the model can't answer: a refresh only queues its update, and by the time it lands the re-render this has to ride is already under way. So the answer is worked out from what we just did — the files we changed report whether the selection covered all of their changes, and the ones it didn't touch are as the model describes them. Co-authored-by: Claude Opus 5 (1M context) --- .../controllers/helpers/diff_line_restore.go | 5 +- pkg/gui/controllers/main_view_controller.go | 37 +++++--- .../controllers/working_tree_diff_actions.go | 91 +++++++++++++++++-- pkg/gui/gui_common.go | 4 + pkg/gui/types/common.go | 4 + .../main_view/focus_follows_staged_side.go | 54 +++++++++++ .../main_view/focus_follows_when_pane_goes.go | 47 ++++++++++ .../focus_returns_when_split_collapses.go | 56 ++++++++++++ pkg/integration/tests/test_list.go | 3 + 9 files changed, 278 insertions(+), 23 deletions(-) create mode 100644 pkg/integration/tests/main_view/focus_follows_staged_side.go create mode 100644 pkg/integration/tests/main_view/focus_follows_when_pane_goes.go create mode 100644 pkg/integration/tests/main_view/focus_returns_when_split_collapses.go diff --git a/pkg/gui/controllers/helpers/diff_line_restore.go b/pkg/gui/controllers/helpers/diff_line_restore.go index 35a2e4337..31cdcd967 100644 --- a/pkg/gui/controllers/helpers/diff_line_restore.go +++ b/pkg/gui/controllers/helpers/diff_line_restore.go @@ -340,7 +340,10 @@ func (self *DiffLineHelper) installDiffLineRestore( findComplete func(contents []gocui.DiffLineContent) (int, bool), place func(viewLine int), ) { - manager := self.c.GetViewBufferManagerForView(view) + // Get-or-create, because the pane may not have rendered anything yet: a file whose + // diff has only just become split has a second pane whose first render is the one + // this restore is for. + manager := self.c.GetOrCreateViewBufferManagerForView(view) if manager == nil { return } diff --git a/pkg/gui/controllers/main_view_controller.go b/pkg/gui/controllers/main_view_controller.go index 71561043c..650529f90 100644 --- a/pkg/gui/controllers/main_view_controller.go +++ b/pkg/gui/controllers/main_view_controller.go @@ -300,33 +300,44 @@ func (self *MainViewController) primaryAction() error { return actions.PrimaryAction(self.context, first, last) } -// revealSelectionAfterAction moves the focused main view's selection to the change -// that takes the place of the one just acted on, once the changed diff has re-rendered. -// Call it from the panel's action handler with the pane it acted in and the buffer line -// the selection starts on, before triggering the re-render. +// revealSelectionAfterAction moves the selection to the change that takes the place of +// the one just acted on, once the changed diff has re-rendered. Call it from the panel's +// action handler with the pane it acted in, the pane the work carries on in, and the +// buffer line the selection starts on, before triggering the re-render. // // The line acted on is gone from the diff, so what is remembered is its place among the // diff's changes: the next change moves up into it, which is where you want to be to // carry on. A range collapses to a single line at its start, and hunk mode selects the -// whole block it lands in, so that pressing the key again acts on the next hunk. -func revealSelectionAfterAction(c *ControllerCommon, pane types.DiffPaneContext, firstBufferLine int) { - view := pane.GetView() - ordinal := c.Helpers().DiffLine.ChangeLineOrdinal(view, firstBufferLine) +// whole block it lands in, so that pressing the key again acts on the next hunk. The +// target pane inherits that select mode, this being the same piece of work continuing +// in another pane — and shows no selection until the restore places one, so that what +// it was left showing the last time it was used doesn't appear for a frame. +func revealSelectionAfterAction( + c *ControllerCommon, source types.DiffPaneContext, target types.DiffPaneContext, firstBufferLine int, +) { + ordinal := c.Helpers().DiffLine.ChangeLineOrdinal(source.GetView(), firstBufferLine) - sel := pane.DiffSelectState() + sel := source.DiffSelectState() if sel.Mode == types.DiffSelectModeRange { sel.Mode = types.DiffSelectModeLine sel.RangeIsSticky = false } + *target.DiffSelectState() = *sel selectHunk := sel.Mode == types.DiffSelectModeHunk - c.Helpers().DiffLine.RevealChangeLineAtOrdinal(view, ordinal, func(viewLine int) { + targetView := target.GetView() + if target != source { + target.SetHasSelectableContent(false) + c.Context().UpdateSelectionHighlights() + } + + c.Helpers().DiffLine.RevealChangeLineAtOrdinal(targetView, ordinal, func(viewLine int) { if selectHunk { - c.Helpers().DiffLine.SelectChangeBlock(pane, viewLine, true) + c.Helpers().DiffLine.SelectChangeBlock(target, viewLine, true) return } - view.CancelRangeSelect() - c.Helpers().DiffLine.ShowSelectionAtLine(view, viewLine, true) + targetView.CancelRangeSelect() + c.Helpers().DiffLine.ShowSelectionAtLine(targetView, viewLine, true) }) } diff --git a/pkg/gui/controllers/working_tree_diff_actions.go b/pkg/gui/controllers/working_tree_diff_actions.go index 2cc5a0282..c43e85b0a 100644 --- a/pkg/gui/controllers/working_tree_diff_actions.go +++ b/pkg/gui/controllers/working_tree_diff_actions.go @@ -99,20 +99,35 @@ func (self *WorkingTreeDiffActions) applyDiffLineSelection( // A directory's diff spans several files, and a patch is of one file, so the // selected lines are grouped by the file they belong to and applied file by file. infosByFile := lo.GroupBy(infos, func(info types.DiffLineInfo) string { return info.Path }) + acted := set.New[string]() + actedSideRemains := false for path, fileInfos := range infosByFile { file := self.fileForDiffLinePath(path) if file == nil { continue } - if err := self.applyDiffLines(file, fileInfos, onStagedSide, opts); err != nil { + changesLeft, err := self.applyDiffLines(file, fileInfos, onStagedSide, opts) + if err != nil { return err } + acted.Add(file.GetPath()) + actedSideRemains = actedSideRemains || changesLeft } + if !actedSideRemains { + actedSideRemains = self.anyFileHasChangesOnSide(acted, onStagedSide) + } + + // Whether the other side has anything decides which pane the work carries on in. + // If the lines were staged, they are in the index now, so that side has them. If + // they were discarded, the other side was not touched, so the model still + // describes it correctly. + otherSideHasChanges := opts.Cached || self.anyFileHasChangesOnSide(set.New[string](), !onStagedSide) // The refresh below queues the re-render of the diff we just changed; this rides it, // so that the selection ends up on the change that took the place of the one acted - // on rather than at a position that means nothing any more. - revealSelectionAfterAction(self.c, pane, firstBufferLine) + // on rather than at a position that means nothing any more — and in the pane the + // work carries on in, which is not always the one it was in. + self.revealSelectionInPaneItLandsIn(pane, firstBufferLine, actedSideRemains, otherSideHasChanges) // Block input until the refresh has landed, so that a quick second keypress acts on // the diff as it now is rather than on the one we just changed. @@ -145,9 +160,13 @@ func (self *WorkingTreeDiffActions) fileForDiffLinePath(path string) *models.Fil // position in the new file and differ only in being a deletion. Context lines are not // selected: a patch of the lines you picked keeps whatever context it needs around // them by itself. +// +// It reports whether the diff it read holds changes the selection didn't cover. The +// caller uses this to tell whether the side acted on still has anything of this file +// in it once we are done. func (self *WorkingTreeDiffActions) applyDiffLines( file *models.File, infos []types.DiffLineInfo, sourceCached bool, opts git_commands.ApplyPatchOpts, -) error { +) (bool, error) { parsedPatch := patch.Parse(self.c.Git().WorkingTree.WorktreeFileDiff(file, true, sourceCached)) type changeLine struct { @@ -179,17 +198,19 @@ func (self *WorkingTreeDiffActions) applyDiffLines( } } + changesLeft := len(patchLineIndices) < changeLineCount(parsedPatch) + // Acting on every change of a file is acting on the file itself, and saying so is // not the same as applying its diff. The diff of a deleted file is its content // going away, and putting that into the index line by line leaves an empty file // there rather than the deletion; the diff of an added one is its whole content, // and taking that back out leaves an empty file in the index rather than an // untracked one. - if opts.Cached && len(patchLineIndices) == changeLineCount(parsedPatch) { + if !changesLeft && opts.Cached { if opts.Reverse { - return self.c.Git().WorkingTree.UnStageFile(file.Names(), file.Tracked) + return false, self.c.Git().WorkingTree.UnStageFile(file.Names(), file.Tracked) } - return self.c.Git().WorkingTree.StageFile(file.GetPath()) + return false, self.c.Git().WorkingTree.StageFile(file.GetPath()) } patchToApply := parsedPatch. @@ -200,10 +221,10 @@ func (self *WorkingTreeDiffActions) applyDiffLines( }). FormatPlain() if patchToApply == "" { - return nil + return changesLeft, nil } - return self.c.Git().Patch.ApplyPatch(patchToApply, opts) + return changesLeft, self.c.Git().Patch.ApplyPatch(patchToApply, opts) } // changeLineCount returns how many of a patch's lines are changes rather than context @@ -213,3 +234,55 @@ func changeLineCount(p *patch.Patch) int { return line.IsAddition() || line.IsDeletion() }) } + +// revealSelectionInPaneItLandsIn arranges for the selection to carry on where the work +// does, which is not always the pane it was in. +// +// Each side of the diff has a pane of its own, so acting on one usually leaves +// everything where it is. But a pane is only shown while its side has something in it: +// staging the last unstaged change takes the upper pane away, and unstaging the last +// staged one takes the lower one away. The refresh moves the focus into whichever pane +// is left, and this puts the selection there to meet it — on the lines just acted on, +// which are in that pane now, unless they were discarded rather than moved, in which +// case on what is left of the file. +func (self *WorkingTreeDiffActions) revealSelectionInPaneItLandsIn( + pane types.DiffPaneContext, firstBufferLine int, actedSideRemains bool, otherSideHasChanges bool, +) { + target := pane + if !actedSideRemains && otherSideHasChanges { + target = self.otherPane(pane) + } + + revealSelectionAfterAction(self.c, pane, target, firstBufferLine) +} + +// otherPane returns the main pane that isn't the given one. +func (self *WorkingTreeDiffActions) otherPane(pane types.DiffPaneContext) types.DiffPaneContext { + if pane.GetKey() == self.c.Contexts().Normal.GetKey() { + return self.c.Contexts().NormalSecondary + } + return self.c.Contexts().Normal +} + +// anyFileHasChangesOnSide reports whether any file under the selected node, other than +// the ones named by except, has changes on the given side of the index, as the model +// has them. The model is right about any file the action didn't touch; the ones it did +// touch report for themselves, their entry not being right until the refresh lands. +func (self *WorkingTreeDiffActions) anyFileHasChangesOnSide(except *set.Set[string], staged bool) bool { + node := self.context().GetSelected() + if node == nil { + return false + } + + found := false + _ = node.ForEachFile(func(file *models.File) error { + if except.Includes(file.GetPath()) { + return nil + } + if (staged && file.HasStagedChanges) || (!staged && file.HasUnstagedChanges) { + found = true + } + return nil + }) + return found +} diff --git a/pkg/gui/gui_common.go b/pkg/gui/gui_common.go index d693fd77f..f2b7c50ab 100644 --- a/pkg/gui/gui_common.go +++ b/pkg/gui/gui_common.go @@ -185,6 +185,10 @@ func (self *guiCommon) GetViewBufferManagerForView(view *gocui.View) *tasks.View return self.gui.getViewBufferManagerForView(view) } +func (self *guiCommon) GetOrCreateViewBufferManagerForView(view *gocui.View) *tasks.ViewBufferManager { + return self.gui.getManager(view) +} + func (self *guiCommon) ReadLinesToFillView(view *gocui.View) { self.gui.readLinesToFillView(view) } diff --git a/pkg/gui/types/common.go b/pkg/gui/types/common.go index 1baf6b3f9..6f77c7856 100644 --- a/pkg/gui/types/common.go +++ b/pkg/gui/types/common.go @@ -72,6 +72,10 @@ type IGuiCommon interface { // return the view buffer manager for the given view, or nil if it doesn't have one GetViewBufferManagerForView(view *gocui.View) *tasks.ViewBufferManager + // return the view buffer manager for the given view, making one if the view has + // never rendered anything, for saying something about a render still to come + GetOrCreateViewBufferManagerForView(view *gocui.View) *tasks.ViewBufferManager + // read enough lines into the given view's buffer to fill it at its current // scroll position, plus some read-ahead for smooth scrolling ReadLinesToFillView(view *gocui.View) diff --git a/pkg/integration/tests/main_view/focus_follows_staged_side.go b/pkg/integration/tests/main_view/focus_follows_staged_side.go new file mode 100644 index 000000000..2bccad47b --- /dev/null +++ b/pkg/integration/tests/main_view/focus_follows_staged_side.go @@ -0,0 +1,54 @@ +package main_view + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var FocusFollowsStagedSide = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Unstaging from a fully staged file leaves the focus on the staged side, which keeps its pane", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInStagingView = false + }, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("file1", "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\nnine\nten\n") + shell.Commit("one") + + // Two staged additions and nothing unstaged, so only the pane the staged side + // lives in is shown. + shell.UpdateFileAndAdd("file1", "one\nSTAGED1\ntwo\nthree\nfour\nfive\nsix\nseven\nSTAGED2\neight\nnine\nten\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Files(). + IsFocused(). + Lines( + Contains("M file1").IsSelected(), + ). + Press(keys.Universal.FocusMainView) + + t.Views().Main().IsInvisible() + t.Views().Secondary(). + IsFocused(). + Title(Equals("Staged changes")). + SelectedLines( + Contains("+STAGED1"), + ). + PressPrimaryAction() + + // The line taken out of the index turns up in the pane that has just appeared + // above, and the work carries on where it was, on the next staged change. + t.Views().Files().Lines( + Contains("MM file1"), + ) + t.Views().Main(). + IsVisible(). + Content(Contains("+STAGED1")) + t.Views().Secondary(). + IsFocused(). + SelectedLines( + Contains("+STAGED2"), + ) + }, +}) diff --git a/pkg/integration/tests/main_view/focus_follows_when_pane_goes.go b/pkg/integration/tests/main_view/focus_follows_when_pane_goes.go new file mode 100644 index 000000000..c4423f9e0 --- /dev/null +++ b/pkg/integration/tests/main_view/focus_follows_when_pane_goes.go @@ -0,0 +1,47 @@ +package main_view + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var FocusFollowsWhenPaneGoes = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Staging the last unstaged change takes the upper pane away, so the focus follows the lines into the lower one", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInStagingView = false + }, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("file1", "one\ntwo\nthree\n") + shell.Commit("one") + + shell.UpdateFile("file1", "one\nADDED\ntwo\nthree\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Files(). + IsFocused(). + Press(keys.Universal.FocusMainView) + + t.Views().Main(). + IsFocused(). + Title(Equals("Unstaged changes")). + SelectedLines( + Contains("+ADDED"), + ). + PressPrimaryAction() + + // Nothing is unstaged any more, so that pane is gone and the line is in the one + // below, where the focus and the selection now are. + t.Views().Files().Lines( + Contains("M file1"), + ) + t.Views().Main().IsInvisible() + t.Views().Secondary(). + IsFocused(). + Title(Equals("Staged changes")). + SelectedLines( + Contains("+ADDED"), + ) + }, +}) diff --git a/pkg/integration/tests/main_view/focus_returns_when_split_collapses.go b/pkg/integration/tests/main_view/focus_returns_when_split_collapses.go new file mode 100644 index 000000000..b0f031e1d --- /dev/null +++ b/pkg/integration/tests/main_view/focus_returns_when_split_collapses.go @@ -0,0 +1,56 @@ +package main_view + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var FocusReturnsWhenSplitCollapses = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Unstaging the last staged change from the secondary pane brings the focus back to the main one", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInStagingView = false + }, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("file1", "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\nnine\nten\n") + shell.Commit("one") + + // One change on each side, so the diff is split. + shell.UpdateFileAndAdd("file1", "one\nSTAGED\ntwo\nthree\nfour\nfive\nsix\nseven\neight\nnine\nten\n") + shell.UpdateFile("file1", "one\nSTAGED\ntwo\nthree\nfour\nfive\nsix\nseven\nUNSTAGED\neight\nnine\nten\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Files(). + IsFocused(). + Lines( + Contains("MM file1").IsSelected(), + ). + Press(keys.Universal.FocusMainView) + + t.Views().Main(). + IsFocused(). + Press(keys.Universal.TogglePanel) + + t.Views().Secondary(). + IsFocused(). + SelectedLines( + Contains("+STAGED"), + ). + PressPrimaryAction() + + // With nothing staged left the diff isn't split any more, so the pane that was + // showing the staged side is gone — and the focus is back on the main one, where + // the change just taken out of the index now is. + t.Views().Files().Lines( + Contains(" M file1"), + ) + t.Views().Main(). + IsFocused(). + Content(Contains("+STAGED")). + Content(Contains("+UNSTAGED")). + SelectedLines( + Contains("+STAGED"), + ) + }, +}) diff --git a/pkg/integration/tests/test_list.go b/pkg/integration/tests/test_list.go index bcdf37e43..a02927d04 100644 --- a/pkg/integration/tests/test_list.go +++ b/pkg/integration/tests/test_list.go @@ -377,7 +377,10 @@ var tests = []*components.IntegrationTest{ main_view.FileNavigationScrollsToTheTop, main_view.FocusFollowsAPaneEmptiedFromOutside, main_view.FocusFollowsIntoAPaneTakingOver, + main_view.FocusFollowsStagedSide, + main_view.FocusFollowsWhenPaneGoes, main_view.FocusLeavesAnAlwaysSplitEmptyPane, + main_view.FocusReturnsWhenSplitCollapses, main_view.HideSelectionWhenChangesVanish, main_view.KeepAWrappedLineCoveredAcrossARerender, main_view.KeepBothHalvesOfAChangeSelected, From 0cb134539394215e4da9d7a0bddaab191505caf1 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Sun, 16 Aug 2026 07:30:43 +0200 Subject: [PATCH 11/21] Discard the selected diff lines from the focused main view MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The remove key now works on a diff selection the way it does in the staging view: on the unstaged side it throws the selected lines away, which it asks about first, and on the staged side it takes them out of the index, which is unstaging and needs no warning. It goes through the same path as staging, so that everything around the action behaves identically — the selection lands on the change that took the place of the discarded one, and the focus follows the side it acted on. Co-authored-by: Claude Opus 5 (1M context) --- docs-master/keybindings/Keybindings_en.md | 2 + docs-master/keybindings/Keybindings_ja.md | 2 + docs-master/keybindings/Keybindings_ko.md | 2 + docs-master/keybindings/Keybindings_nl.md | 2 + docs-master/keybindings/Keybindings_pl.md | 2 + docs-master/keybindings/Keybindings_pt.md | 2 + docs-master/keybindings/Keybindings_ru.md | 2 + docs-master/keybindings/Keybindings_zh-CN.md | 2 + docs-master/keybindings/Keybindings_zh-TW.md | 2 + pkg/gui/controllers/main_view_controller.go | 24 +++++++ .../controllers/working_tree_diff_actions.go | 29 ++++++++ pkg/gui/types/context.go | 4 ++ .../tests/main_view/discard_diff_lines.go | 70 +++++++++++++++++++ pkg/integration/tests/test_list.go | 1 + 14 files changed, 146 insertions(+) create mode 100644 pkg/integration/tests/main_view/discard_diff_lines.go diff --git a/docs-master/keybindings/Keybindings_en.md b/docs-master/keybindings/Keybindings_en.md index 749cdd9e8..63bb3a24c 100644 --- a/docs-master/keybindings/Keybindings_en.md +++ b/docs-master/keybindings/Keybindings_en.md @@ -227,6 +227,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` v `` | Toggle range select | | | `` e `` | Edit file | Open file in external editor. | | `` `` | Stage | Toggle selection staged / unstaged. | +| `` d `` | Discard | When unstaged change is selected, discard the change using `git reset`. When staged change is selected, unstage the change. | | `` `` | Copy selected text to clipboard | | | `` , h `` | Go to previous hunk | | | `` , l `` | Go to next hunk | | @@ -341,6 +342,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` v `` | Toggle range select | | | `` e `` | Edit file | Open file in external editor. | | `` `` | Stage | Toggle selection staged / unstaged. | +| `` d `` | Discard | When unstaged change is selected, discard the change using `git reset`. When staged change is selected, unstage the change. | | `` `` | Copy selected text to clipboard | | | `` , h `` | Go to previous hunk | | | `` , l `` | Go to next hunk | | diff --git a/docs-master/keybindings/Keybindings_ja.md b/docs-master/keybindings/Keybindings_ja.md index 331becbd0..786750b16 100644 --- a/docs-master/keybindings/Keybindings_ja.md +++ b/docs-master/keybindings/Keybindings_ja.md @@ -196,6 +196,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` v `` | 範囲選択を切り替え | | | `` e `` | ファイルを編集 | 外部エディタでファイルを開きます。 | | `` `` | ステージ | 選択された部分のステージ / アンステージを切り替えます。 | +| `` d `` | 破棄 | ステージされていない変更が選択されている場合、`git reset`を使用して変更を破棄します。ステージされた変更が選択されている場合、変更をアンステージします。 | | `` `` | 選択したテキストをクリップボードにコピー | | | `` , h `` | 前のハンクに移動 | | | `` , l `` | 次のハンクに移動 | | @@ -318,6 +319,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` v `` | 範囲選択を切り替え | | | `` e `` | ファイルを編集 | 外部エディタでファイルを開きます。 | | `` `` | ステージ | 選択された部分のステージ / アンステージを切り替えます。 | +| `` d `` | 破棄 | ステージされていない変更が選択されている場合、`git reset`を使用して変更を破棄します。ステージされた変更が選択されている場合、変更をアンステージします。 | | `` `` | 選択したテキストをクリップボードにコピー | | | `` , h `` | 前のハンクに移動 | | | `` , l `` | 次のハンクに移動 | | diff --git a/docs-master/keybindings/Keybindings_ko.md b/docs-master/keybindings/Keybindings_ko.md index adf015638..3adec5eb8 100644 --- a/docs-master/keybindings/Keybindings_ko.md +++ b/docs-master/keybindings/Keybindings_ko.md @@ -88,6 +88,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` v `` | 드래그 선택 전환 | | | `` e `` | 파일 편집 | Open file in external editor. | | `` `` | Staged 전환 | 선택한 행을 staged / unstaged | +| `` d `` | 변경을 삭제 (git reset) | When unstaged change is selected, discard the change using `git reset`. When staged change is selected, unstage the change. | | `` `` | 선택한 텍스트를 클립보드에 복사 | | | `` , h `` | 이전 hunk를 선택 | | | `` , l `` | 다음 hunk를 선택 | | @@ -175,6 +176,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` v `` | 드래그 선택 전환 | | | `` e `` | 파일 편집 | Open file in external editor. | | `` `` | Staged 전환 | 선택한 행을 staged / unstaged | +| `` d `` | 변경을 삭제 (git reset) | When unstaged change is selected, discard the change using `git reset`. When staged change is selected, unstage the change. | | `` `` | 선택한 텍스트를 클립보드에 복사 | | | `` , h `` | 이전 hunk를 선택 | | | `` , l `` | 다음 hunk를 선택 | | diff --git a/docs-master/keybindings/Keybindings_nl.md b/docs-master/keybindings/Keybindings_nl.md index e2db96275..065a98df2 100644 --- a/docs-master/keybindings/Keybindings_nl.md +++ b/docs-master/keybindings/Keybindings_nl.md @@ -235,6 +235,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` v `` | Toggle drag selecteer | | | `` e `` | Verander bestand | Open bestand in externe editor. | | `` `` | Toggle staged | Toggle lijnen staged / unstaged | +| `` d `` | Verwijdert change (git reset) | When unstaged change is selected, discard the change using `git reset`. When staged change is selected, unstage the change. | | `` `` | Copy selected text to clipboard | | | `` , h `` | Selecteer de vorige hunk | | | `` , l `` | Selecteer de volgende hunk | | @@ -319,6 +320,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` v `` | Toggle drag selecteer | | | `` e `` | Verander bestand | Open bestand in externe editor. | | `` `` | Toggle staged | Toggle lijnen staged / unstaged | +| `` d `` | Verwijdert change (git reset) | When unstaged change is selected, discard the change using `git reset`. When staged change is selected, unstage the change. | | `` `` | Copy selected text to clipboard | | | `` , h `` | Selecteer de vorige hunk | | | `` , l `` | Selecteer de volgende hunk | | diff --git a/docs-master/keybindings/Keybindings_pl.md b/docs-master/keybindings/Keybindings_pl.md index 0b1f4c763..58d7eeb80 100644 --- a/docs-master/keybindings/Keybindings_pl.md +++ b/docs-master/keybindings/Keybindings_pl.md @@ -103,6 +103,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` v `` | Przełącz zaznaczenie zakresu | | | `` e `` | Edytuj plik | Otwórz plik w zewnętrznym edytorze. | | `` `` | Zatwierdź | Przełącz zaznaczenie zatwierdzone/niezatwierdzone. | +| `` d `` | Odrzuć | Gdy zaznaczona jest niezatwierdzona zmiana, odrzuć ją używając `git reset`. Gdy zaznaczona jest zatwierdzona zmiana, cofnij zatwierdzenie. | | `` `` | Kopiuj zaznaczony tekst do schowka | | | `` , h `` | Idź do poprzedniego fragmentu | | | `` , l `` | Idź do następnego fragmentu | | @@ -214,6 +215,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` v `` | Przełącz zaznaczenie zakresu | | | `` e `` | Edytuj plik | Otwórz plik w zewnętrznym edytorze. | | `` `` | Zatwierdź | Przełącz zaznaczenie zatwierdzone/niezatwierdzone. | +| `` d `` | Odrzuć | Gdy zaznaczona jest niezatwierdzona zmiana, odrzuć ją używając `git reset`. Gdy zaznaczona jest zatwierdzona zmiana, cofnij zatwierdzenie. | | `` `` | Kopiuj zaznaczony tekst do schowka | | | `` , h `` | Idź do poprzedniego fragmentu | | | `` , l `` | Idź do następnego fragmentu | | diff --git a/docs-master/keybindings/Keybindings_pt.md b/docs-master/keybindings/Keybindings_pt.md index 8f8d2814b..ff80a02db 100644 --- a/docs-master/keybindings/Keybindings_pt.md +++ b/docs-master/keybindings/Keybindings_pt.md @@ -239,6 +239,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` v `` | Toggle range select | | | `` e `` | Editar arquivo | Abrir arquivo no editor externo. | | `` `` | Etapa | Ativar/desativar seleção em staged/unstaged | +| `` d `` | Descartar | Quando a mudança não desejada for selecionada, descarte a mudança usando `git reset`. Quando a mudança em fase é selecionada, despare a mudança. | | `` `` | Copiar texto selecionado para área de transferência | | | `` , h `` | Ir para o local anterior | | | `` , l `` | Ir para o próximo trecho | | @@ -350,6 +351,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` v `` | Toggle range select | | | `` e `` | Editar arquivo | Abrir arquivo no editor externo. | | `` `` | Etapa | Ativar/desativar seleção em staged/unstaged | +| `` d `` | Descartar | Quando a mudança não desejada for selecionada, descarte a mudança usando `git reset`. Quando a mudança em fase é selecionada, despare a mudança. | | `` `` | Copiar texto selecionado para área de transferência | | | `` , h `` | Ir para o local anterior | | | `` , l `` | Ir para o próximo trecho | | diff --git a/docs-master/keybindings/Keybindings_ru.md b/docs-master/keybindings/Keybindings_ru.md index 399e86305..7545311a0 100644 --- a/docs-master/keybindings/Keybindings_ru.md +++ b/docs-master/keybindings/Keybindings_ru.md @@ -78,6 +78,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` v `` | Переключить выборку перетаскивания | | | `` e `` | Редактировать файл | Open file in external editor. | | `` `` | Переключить индекс | Переключить строку в проиндексированные / непроиндексированные | +| `` d `` | Отменить изменение (git reset) | When unstaged change is selected, discard the change using `git reset`. When staged change is selected, unstage the change. | | `` `` | Скопировать выделенный текст в буфер обмена | | | `` , h `` | Выбрать предыдущую часть | | | `` , l `` | Выбрать следующую часть | | @@ -119,6 +120,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` v `` | Переключить выборку перетаскивания | | | `` e `` | Редактировать файл | Open file in external editor. | | `` `` | Переключить индекс | Переключить строку в проиндексированные / непроиндексированные | +| `` d `` | Отменить изменение (git reset) | When unstaged change is selected, discard the change using `git reset`. When staged change is selected, unstage the change. | | `` `` | Скопировать выделенный текст в буфер обмена | | | `` , h `` | Выбрать предыдущую часть | | | `` , l `` | Выбрать следующую часть | | diff --git a/docs-master/keybindings/Keybindings_zh-CN.md b/docs-master/keybindings/Keybindings_zh-CN.md index 9e12bc5d2..a18cd0177 100644 --- a/docs-master/keybindings/Keybindings_zh-CN.md +++ b/docs-master/keybindings/Keybindings_zh-CN.md @@ -290,6 +290,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` v `` | 切换拖动选择 | | | `` e `` | 编辑文件 | 使用外部编辑器打开文件 | | `` `` | 切换暂存状态 | 切换行暂存状态 | +| `` d `` | 取消变更(git reset) | 当选择未暂存的变更时,使用git reset丢弃该变更。当选择已暂存的变更时,取消暂存该变更 | | `` `` | 复制选中文本到剪贴板 | | | `` , h `` | 选择上一个区块 | | | `` , l `` | 选择下一个区块 | | @@ -347,6 +348,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` v `` | 切换拖动选择 | | | `` e `` | 编辑文件 | 使用外部编辑器打开文件 | | `` `` | 切换暂存状态 | 切换行暂存状态 | +| `` d `` | 取消变更(git reset) | 当选择未暂存的变更时,使用git reset丢弃该变更。当选择已暂存的变更时,取消暂存该变更 | | `` `` | 复制选中文本到剪贴板 | | | `` , h `` | 选择上一个区块 | | | `` , l `` | 选择下一个区块 | | diff --git a/docs-master/keybindings/Keybindings_zh-TW.md b/docs-master/keybindings/Keybindings_zh-TW.md index 2adf9ac93..7edb92940 100644 --- a/docs-master/keybindings/Keybindings_zh-TW.md +++ b/docs-master/keybindings/Keybindings_zh-TW.md @@ -79,6 +79,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` v `` | 切換拖曳選擇 | | | `` e `` | 編輯檔案 | 使用外部編輯器開啟 | | `` `` | 切換預存 | 切換現有行的狀態 (已預存/未預存) | +| `` d `` | 刪除變更 (git reset) | 選取未暫存的變更時,使用 `git reset` 捨棄變更。選取已暫存的變更時,取消暫存變更。 | | `` `` | 複製所選文本至剪貼簿 | | | `` , h `` | 選擇上一段 | | | `` , l `` | 選擇下一段 | | @@ -369,6 +370,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` v `` | 切換拖曳選擇 | | | `` e `` | 編輯檔案 | 使用外部編輯器開啟 | | `` `` | 切換預存 | 切換現有行的狀態 (已預存/未預存) | +| `` d `` | 刪除變更 (git reset) | 選取未暫存的變更時,使用 `git reset` 捨棄變更。選取已暫存的變更時,取消暫存變更。 | | `` `` | 複製所選文本至剪貼簿 | | | `` , h `` | 選擇上一段 | | | `` , l `` | 選擇下一段 | | diff --git a/pkg/gui/controllers/main_view_controller.go b/pkg/gui/controllers/main_view_controller.go index 650529f90..2e8874c6b 100644 --- a/pkg/gui/controllers/main_view_controller.go +++ b/pkg/gui/controllers/main_view_controller.go @@ -88,6 +88,15 @@ func (self *MainViewController) GetKeybindings(opts types.KeybindingsOpts) []*ty Tooltip: self.c.Tr.StageSelectionTooltip, DisplayOnScreen: true, }, + { + Keys: opts.GetKeys(opts.Config.Universal.Remove), + Handler: self.discardSelection, + Description: self.c.Tr.DiscardSelection, + DescriptionFunc: self.workingTreeActionDescription(self.c.Tr.DiscardSelection), + GetDisabledReason: self.diffSelectionDisabledReason, + Tooltip: self.c.Tr.DiscardSelectionTooltip, + DisplayOnScreen: true, + }, { Keys: opts.GetKeys(opts.Config.Universal.CopyToClipboard), Handler: self.copySelection, @@ -341,6 +350,21 @@ func revealSelectionAfterAction( }) } +// discardSelection takes the selected diff lines back out of what they are part of, +// which — like the primary action — is the panel's business, and so is the re-render +// that follows. +func (self *MainViewController) discardSelection() error { + actions := self.focusedMainViewActions() + if actions == nil { + return nil + } + first, last, ok := self.context.GetView().SelectedBufferLineRange() + if !ok { + return nil + } + return actions.DiscardSelection(self.context, first, last) +} + // workingTreeActionDescription gives a command's description only where the command // applies — over the working tree's diff — so that it is listed there and nowhere else. func (self *MainViewController) workingTreeActionDescription(description string) func() string { diff --git a/pkg/gui/controllers/working_tree_diff_actions.go b/pkg/gui/controllers/working_tree_diff_actions.go index c43e85b0a..00f3fab1c 100644 --- a/pkg/gui/controllers/working_tree_diff_actions.go +++ b/pkg/gui/controllers/working_tree_diff_actions.go @@ -70,6 +70,35 @@ func (self *WorkingTreeDiffActions) PrimaryAction(pane types.DiffPaneContext, fi git_commands.ApplyPatchOpts{Reverse: onStagedSide, Cached: true}) } +// DiscardSelection takes the selected diff lines out of the working tree — or, on the +// staged side, out of the index, which is where "discard this" means "I don't want it +// staged". +func (self *WorkingTreeDiffActions) DiscardSelection(pane types.DiffPaneContext, firstBufferLine int, lastBufferLine int) error { + if self.c.UserConfig().Git.DiffContextSize == 0 { + return fmt.Errorf(self.c.Tr.Actions.NotEnoughContextToDiscard, + self.c.UserConfig().Keybinding.Universal.IncreaseContextInDiffView) + } + + infos, onStagedSide, ok := self.diffLineSelection(pane, firstBufferLine, lastBufferLine) + if !ok { + return nil + } + + // Either way the change is applied backwards; which side it is applied to decides + // how destructive that is. On the staged side it goes to the index; this is the + // same as unstaging, so nothing is lost. On the unstaged side it goes to the + // working tree, where the change is gone for good, so we ask first. + return self.c.ConfirmIf(!onStagedSide && !self.c.UserConfig().Gui.SkipDiscardChangeWarning, + types.ConfirmOpts{ + Title: self.c.Tr.DiscardChangeTitle, + Prompt: self.c.Tr.DiscardChangePrompt, + HandleConfirm: func() error { + return self.applyDiffLineSelection(pane, firstBufferLine, infos, onStagedSide, + git_commands.ApplyPatchOpts{Reverse: true, Cached: onStagedSide}) + }, + }) +} + // diffLineSelection resolves what the user has selected in a pane of the focused main // view to the change lines to act on, and reports whether they are the staged side of // the diff — which is a question about the pane, so it is the same for every file of a diff --git a/pkg/gui/types/context.go b/pkg/gui/types/context.go index f468687d9..4950dfc9d 100644 --- a/pkg/gui/types/context.go +++ b/pkg/gui/types/context.go @@ -255,6 +255,10 @@ type FocusedMainViewActions interface { // single line, a range, or a hunk. The panel re-renders the diff itself, being the // one that knows what it did to it. PrimaryAction(pane DiffPaneContext, firstBufferLine int, lastBufferLine int) error + + // DiscardSelection takes the selected diff lines back out of whatever they are part + // of: the working tree for the files panel. + DiscardSelection(pane DiffPaneContext, firstBufferLine int, lastBufferLine int) error } type IListContext interface { diff --git a/pkg/integration/tests/main_view/discard_diff_lines.go b/pkg/integration/tests/main_view/discard_diff_lines.go new file mode 100644 index 000000000..699b4d506 --- /dev/null +++ b/pkg/integration/tests/main_view/discard_diff_lines.go @@ -0,0 +1,70 @@ +package main_view + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var DiscardDiffLines = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Discard a hunk of the working tree's diff from the focused main view, and unstage one from the staged half", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInStagingView = false + }, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("file1", "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\nnine\nten\n") + shell.Commit("one") + + shell.UpdateFileAndAdd("file1", "one\nSTAGED\ntwo\nthree\nfour\nfive\nsix\nseven\neight\nnine\nten\n") + shell.UpdateFile("file1", "one\nSTAGED\ntwo\nthree\nfour\nfive\nsix\nseven\nUNSTAGED\neight\nnine\nten\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Files(). + IsFocused(). + Lines( + Contains("MM file1").IsSelected(), + ). + Press(keys.Universal.FocusMainView) + + // Discarding from the unstaged side throws the change away, so it asks first. + t.Views().Main(). + IsFocused(). + SelectedLines( + Contains("+UNSTAGED"), + ). + Press(keys.Universal.Remove). + Tap(func() { + t.ExpectPopup().Confirmation(). + Title(Equals("Discard change")). + Content(Contains("Are you sure you want to discard this change")). + Confirm() + }) + + // Nothing is unstaged any more, so that pane is gone and the focus has followed + // the file's remaining changes into the staged one. + t.Views().Files().Lines( + Contains("M file1"), + ) + t.Views().Main().IsInvisible() + + // There the same key means "I don't want this staged", which is unstaging, so it + // doesn't ask. + t.Views().Secondary(). + IsFocused(). + Title(Equals("Staged changes")). + SelectedLines( + Contains("+STAGED"), + ). + Press(keys.Universal.Remove) + + t.Views().Files().Lines( + Contains(" M file1"), + ) + t.Views().Secondary().IsInvisible() + t.Views().Main(). + IsFocused(). + Title(Equals("Unstaged changes")). + Content(Contains("+STAGED")) + }, +}) diff --git a/pkg/integration/tests/test_list.go b/pkg/integration/tests/test_list.go index a02927d04..50efa3102 100644 --- a/pkg/integration/tests/test_list.go +++ b/pkg/integration/tests/test_list.go @@ -370,6 +370,7 @@ var tests = []*components.IntegrationTest{ main_view.ClickSelectsDiffLine, main_view.CopyRowsThatAreNoDiffLine, main_view.CopySelectedDiffLines, + main_view.DiscardDiffLines, main_view.DragRangeWithAutoscroll, main_view.DragSelectsDiffLineRange, main_view.EditSelectedDiffLine, From ae538a85830a5f0e49c0785e5bb9017cd73bc0b7 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Sun, 16 Aug 2026 07:34:10 +0200 Subject: [PATCH 12/21] Commit and find a fixup base from the focused main view MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Staging in the main view leaves you looking at the working tree's diff with everything you meant to stage in the index — and, until now, having to go back to the files panel to commit it. The commit keys, and the one that finds the commit a fixup belongs to, are offered there too, so that the whole staging-to-committing round happens in one place. They act on the working tree, which the main view only sometimes shows, so they do nothing over a commit's or a stash's diff — browsing history can't commit by accident — and are listed only where they do something. The check happens per press: what the main view is showing changes as the user moves about, while the bindings are registered once. Co-authored-by: Claude Opus 5 (1M context) --- docs-master/keybindings/Keybindings_en.md | 8 +++ docs-master/keybindings/Keybindings_ja.md | 8 +++ docs-master/keybindings/Keybindings_ko.md | 8 +++ docs-master/keybindings/Keybindings_nl.md | 8 +++ docs-master/keybindings/Keybindings_pl.md | 8 +++ docs-master/keybindings/Keybindings_pt.md | 8 +++ docs-master/keybindings/Keybindings_ru.md | 8 +++ docs-master/keybindings/Keybindings_zh-CN.md | 8 +++ docs-master/keybindings/Keybindings_zh-TW.md | 8 +++ pkg/gui/controllers/main_view_controller.go | 40 +++++++++++ .../tests/main_view/commit_from_main_view.go | 67 +++++++++++++++++++ pkg/integration/tests/test_list.go | 1 + 12 files changed, 180 insertions(+) create mode 100644 pkg/integration/tests/main_view/commit_from_main_view.go diff --git a/docs-master/keybindings/Keybindings_en.md b/docs-master/keybindings/Keybindings_en.md index 63bb3a24c..20bca0c61 100644 --- a/docs-master/keybindings/Keybindings_en.md +++ b/docs-master/keybindings/Keybindings_en.md @@ -234,6 +234,10 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` N `` | Go to previous file | | | `` n `` | Go to next file | | | `` `` | Exit back to side panel | | +| `` c `` | Commit | Commit staged changes. | +| `` w `` | Commit changes without pre-commit hook | | +| `` C `` | Commit changes using git editor | | +| `` `` | Find base commit for fixup | Find the commit that your current changes are building upon, for the sake of amending/fixing up the commit. This spares you from having to look through your branch's commits one-by-one to see which commit should be amended/fixed up. See docs: | | `` / `` | Search the current view by text | | ## Main panel (patch building) @@ -349,6 +353,10 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` N `` | Go to previous file | | | `` n `` | Go to next file | | | `` `` | Exit back to side panel | | +| `` c `` | Commit | Commit staged changes. | +| `` w `` | Commit changes without pre-commit hook | | +| `` C `` | Commit changes using git editor | | +| `` `` | Find base commit for fixup | Find the commit that your current changes are building upon, for the sake of amending/fixing up the commit. This spares you from having to look through your branch's commits one-by-one to see which commit should be amended/fixed up. See docs: | | `` / `` | Search the current view by text | | ## Stash diff --git a/docs-master/keybindings/Keybindings_ja.md b/docs-master/keybindings/Keybindings_ja.md index 786750b16..6d2767953 100644 --- a/docs-master/keybindings/Keybindings_ja.md +++ b/docs-master/keybindings/Keybindings_ja.md @@ -203,6 +203,10 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` N `` | Go to previous file | | | `` n `` | Go to next file | | | `` `` | サイドパネルに戻る | | +| `` c `` | コミット | ステージされた変更をコミットします。 | +| `` w `` | pre-commitフックなしで変更をコミット | | +| `` C `` | Gitエディタを使用して変更をコミット | | +| `` `` | フィックスアップのベースコミットを検索 | 現在の変更が基づいているコミットを見つけて、コミットの修正/フィックスアップを行います。これにより、ブランチのコミットを一つずつ確認して、どのコミットを修正/フィックスアップすべきかを調べる手間が省けます。詳細はドキュメントを参照: | | `` / `` | 現在のビューをテキストで検索 | | ## タグ @@ -326,6 +330,10 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` N `` | Go to previous file | | | `` n `` | Go to next file | | | `` `` | サイドパネルに戻る | | +| `` c `` | コミット | ステージされた変更をコミットします。 | +| `` w `` | pre-commitフックなしで変更をコミット | | +| `` C `` | Gitエディタを使用して変更をコミット | | +| `` `` | フィックスアップのベースコミットを検索 | 現在の変更が基づいているコミットを見つけて、コミットの修正/フィックスアップを行います。これにより、ブランチのコミットを一つずつ確認して、どのコミットを修正/フィックスアップすべきかを調べる手間が省けます。詳細はドキュメントを参照: | | `` / `` | 現在のビューをテキストで検索 | | ## メニュー diff --git a/docs-master/keybindings/Keybindings_ko.md b/docs-master/keybindings/Keybindings_ko.md index 3adec5eb8..dab679603 100644 --- a/docs-master/keybindings/Keybindings_ko.md +++ b/docs-master/keybindings/Keybindings_ko.md @@ -95,6 +95,10 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` N `` | Go to previous file | | | `` n `` | Go to next file | | | `` `` | Exit back to side panel | | +| `` c `` | 커밋 변경내용 | 스테이징된 변경 사항 커밋. | +| `` w `` | Commit changes without pre-commit hook | | +| `` C `` | Git 편집기를 사용하여 변경 내용을 커밋합니다. | | +| `` `` | Find base commit for fixup | Find the commit that your current changes are building upon, for the sake of amending/fixing up the commit. This spares you from having to look through your branch's commits one-by-one to see which commit should be amended/fixed up. See docs: | | `` / `` | 검색 시작 | | ## Stash @@ -183,6 +187,10 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` N `` | Go to previous file | | | `` n `` | Go to next file | | | `` `` | Exit back to side panel | | +| `` c `` | 커밋 변경내용 | 스테이징된 변경 사항 커밋. | +| `` w `` | Commit changes without pre-commit hook | | +| `` C `` | Git 편집기를 사용하여 변경 내용을 커밋합니다. | | +| `` `` | Find base commit for fixup | Find the commit that your current changes are building upon, for the sake of amending/fixing up the commit. This spares you from having to look through your branch's commits one-by-one to see which commit should be amended/fixed up. See docs: | | `` / `` | 검색 시작 | | ## 메인 패널 (Patch Building) diff --git a/docs-master/keybindings/Keybindings_nl.md b/docs-master/keybindings/Keybindings_nl.md index 065a98df2..f336abffa 100644 --- a/docs-master/keybindings/Keybindings_nl.md +++ b/docs-master/keybindings/Keybindings_nl.md @@ -242,6 +242,10 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` N `` | Go to previous file | | | `` n `` | Go to next file | | | `` `` | Exit back to side panel | | +| `` c `` | Commit veranderingen | Commit gestagede wijzigingen. | +| `` w `` | Commit veranderingen zonder pre-commit hook | | +| `` C `` | Commit veranderingen met de git editor | | +| `` `` | Find base commit for fixup | Vind de commit waar je huidige wijzigingen bovenop zijn gebouwd met als doel die commit te amenden/fixen. Hierdoor hoef je dit niet met de hand te doen. Zie: | | `` / `` | Start met zoeken | | ## Patch bouwen @@ -327,6 +331,10 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` N `` | Go to previous file | | | `` n `` | Go to next file | | | `` `` | Exit back to side panel | | +| `` c `` | Commit veranderingen | Commit gestagede wijzigingen. | +| `` w `` | Commit veranderingen zonder pre-commit hook | | +| `` C `` | Commit veranderingen met de git editor | | +| `` `` | Find base commit for fixup | Vind de commit waar je huidige wijzigingen bovenop zijn gebouwd met als doel die commit te amenden/fixen. Hierdoor hoef je dit niet met de hand te doen. Zie: | | `` / `` | Start met zoeken | | ## Staging diff --git a/docs-master/keybindings/Keybindings_pl.md b/docs-master/keybindings/Keybindings_pl.md index 58d7eeb80..b9f928561 100644 --- a/docs-master/keybindings/Keybindings_pl.md +++ b/docs-master/keybindings/Keybindings_pl.md @@ -110,6 +110,10 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` N `` | Go to previous file | | | `` n `` | Go to next file | | | `` `` | Exit back to side panel | | +| `` c `` | Commit | Zatwierdź zmiany zatwierdzone. | +| `` w `` | Zatwierdź zmiany bez hooka pre-commit | | +| `` C `` | Zatwierdź zmiany używając edytora git | | +| `` `` | Znajdź bazowy commit do poprawki | Znajdź commit, na którym opierają się Twoje obecne zmiany, w celu poprawienia/zmiany commita. To pozwala Ci uniknąć przeglądania commitów w Twojej gałęzi jeden po drugim, aby zobaczyć, który commit powinien być poprawiony/zmieniony. Zobacz dokumentację: | | `` / `` | Szukaj w bieżącym widoku po tekście | | ## Drzewa pracy @@ -222,6 +226,10 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` N `` | Go to previous file | | | `` n `` | Go to next file | | | `` `` | Exit back to side panel | | +| `` c `` | Commit | Zatwierdź zmiany zatwierdzone. | +| `` w `` | Zatwierdź zmiany bez hooka pre-commit | | +| `` C `` | Zatwierdź zmiany używając edytora git | | +| `` `` | Znajdź bazowy commit do poprawki | Znajdź commit, na którym opierają się Twoje obecne zmiany, w celu poprawienia/zmiany commita. To pozwala Ci uniknąć przeglądania commitów w Twojej gałęzi jeden po drugim, aby zobaczyć, który commit powinien być poprawiony/zmieniony. Zobacz dokumentację: | | `` / `` | Szukaj w bieżącym widoku po tekście | | ## Panel główny (scalanie) diff --git a/docs-master/keybindings/Keybindings_pt.md b/docs-master/keybindings/Keybindings_pt.md index ff80a02db..4e4f954e1 100644 --- a/docs-master/keybindings/Keybindings_pt.md +++ b/docs-master/keybindings/Keybindings_pt.md @@ -246,6 +246,10 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` N `` | Go to previous file | | | `` n `` | Go to next file | | | `` `` | Exit back to side panel | | +| `` c `` | Commit | Submeter mudanças em staging | +| `` w `` | Fazer commit de alterações sem pré-commit | | +| `` C `` | Enviar alteração usando um editor Git | | +| `` `` | Encontrar commit da base para corrigir | Encontre o commit em que as suas mudanças atuais estão se baseando, para alterar/consertar o commit. Isso poupa-te você de ter que olhar pelos commits da sua branch um por um para ver qual commit deve ser alterado/consertado
Veja a documentação:
| | `` / `` | Pesquisar na visualização atual por texto | | ## Painel Principal (preparação) @@ -358,6 +362,10 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` N `` | Go to previous file | | | `` n `` | Go to next file | | | `` `` | Exit back to side panel | | +| `` c `` | Commit | Submeter mudanças em staging | +| `` w `` | Fazer commit de alterações sem pré-commit | | +| `` C `` | Enviar alteração usando um editor Git | | +| `` `` | Encontrar commit da base para corrigir | Encontre o commit em que as suas mudanças atuais estão se baseando, para alterar/consertar o commit. Isso poupa-te você de ter que olhar pelos commits da sua branch um por um para ver qual commit deve ser alterado/consertado
Veja a documentação:
| | `` / `` | Pesquisar na visualização atual por texto | | ## Stash diff --git a/docs-master/keybindings/Keybindings_ru.md b/docs-master/keybindings/Keybindings_ru.md index 7545311a0..93b252eae 100644 --- a/docs-master/keybindings/Keybindings_ru.md +++ b/docs-master/keybindings/Keybindings_ru.md @@ -85,6 +85,10 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` N `` | Go to previous file | | | `` n `` | Go to next file | | | `` `` | Exit back to side panel | | +| `` c `` | Сохранить изменения | Commit staged changes. | +| `` w `` | Закоммитить изменения без предварительного хука коммита | | +| `` C `` | Сохранить изменения с помощью редактора git | | +| `` `` | Find base commit for fixup | Find the commit that your current changes are building upon, for the sake of amending/fixing up the commit. This spares you from having to look through your branch's commits one-by-one to see which commit should be amended/fixed up. See docs: | | `` / `` | Найти | | ## Главная панель (Индексирование) @@ -127,6 +131,10 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` N `` | Go to previous file | | | `` n `` | Go to next file | | | `` `` | Exit back to side panel | | +| `` c `` | Сохранить изменения | Commit staged changes. | +| `` w `` | Закоммитить изменения без предварительного хука коммита | | +| `` C `` | Сохранить изменения с помощью редактора git | | +| `` `` | Find base commit for fixup | Find the commit that your current changes are building upon, for the sake of amending/fixing up the commit. This spares you from having to look through your branch's commits one-by-one to see which commit should be amended/fixed up. See docs: | | `` / `` | Найти | | ## Главная панель (Слияние) diff --git a/docs-master/keybindings/Keybindings_zh-CN.md b/docs-master/keybindings/Keybindings_zh-CN.md index a18cd0177..499651f96 100644 --- a/docs-master/keybindings/Keybindings_zh-CN.md +++ b/docs-master/keybindings/Keybindings_zh-CN.md @@ -297,6 +297,10 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` N `` | Go to previous file | | | `` n `` | Go to next file | | | `` `` | 退出回到侧边面板 | | +| `` c `` | 提交变更 | 提交暂存文件 | +| `` w `` | 提交变更而无需预先提交钩子 | | +| `` C `` | 使用 Git 编辑器提交变更 | | +| `` `` | 找到用于修复的基准提交 | 找到您当前变更所基于的提交,以便于修正/改进该提交。这样做可以省去您逐一查看分支提交来确定应该修正/改进哪个提交的麻烦。请参阅文档: | | `` / `` | 开始搜索 | | ## 正在合并 @@ -355,6 +359,10 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` N `` | Go to previous file | | | `` n `` | Go to next file | | | `` `` | 退出回到侧边面板 | | +| `` c `` | 提交变更 | 提交暂存文件 | +| `` w `` | 提交变更而无需预先提交钩子 | | +| `` C `` | 使用 Git 编辑器提交变更 | | +| `` `` | 找到用于修复的基准提交 | 找到您当前变更所基于的提交,以便于修正/改进该提交。这样做可以省去您逐一查看分支提交来确定应该修正/改进哪个提交的麻烦。请参阅文档: | | `` / `` | 开始搜索 | | ## 状态 diff --git a/docs-master/keybindings/Keybindings_zh-TW.md b/docs-master/keybindings/Keybindings_zh-TW.md index 7edb92940..8d6994350 100644 --- a/docs-master/keybindings/Keybindings_zh-TW.md +++ b/docs-master/keybindings/Keybindings_zh-TW.md @@ -86,6 +86,10 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` N `` | Go to previous file | | | `` n `` | Go to next file | | | `` `` | 退出回到側邊面板 | | +| `` c `` | 提交變更 | 提交暫存區變更 | +| `` w `` | 沒有預提交 hook 就提交更改 | | +| `` C `` | 使用 git 編輯器提交變更 | | +| `` `` | 尋找 fixup 的基礎提交 | 找出目前變更所依據的提交,以便 amend/fixup。這樣不必逐一檢視分支中的提交來找出要 amend/fixup 的提交。請見文件: | | `` / `` | 搜尋 | | ## 主面板(合併) @@ -377,6 +381,10 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` N `` | Go to previous file | | | `` n `` | Go to next file | | | `` `` | 退出回到側邊面板 | | +| `` c `` | 提交變更 | 提交暫存區變更 | +| `` w `` | 沒有預提交 hook 就提交更改 | | +| `` C `` | 使用 git 編輯器提交變更 | | +| `` `` | 尋找 fixup 的基礎提交 | 找出目前變更所依據的提交,以便 amend/fixup。這樣不必逐一檢視分支中的提交來找出要 amend/fixup 的提交。請見文件: | | `` / `` | 搜尋 | | ## 狀態 diff --git a/pkg/gui/controllers/main_view_controller.go b/pkg/gui/controllers/main_view_controller.go index 2e8874c6b..62953a844 100644 --- a/pkg/gui/controllers/main_view_controller.go +++ b/pkg/gui/controllers/main_view_controller.go @@ -164,6 +164,32 @@ func (self *MainViewController) GetKeybindings(opts types.KeybindingsOpts) []*ty DescriptionFunc: self.diffSelectionDescriptionText(self.c.Tr.RangeSelectDown), GetDisabledReason: self.diffSelectionDisabledReason, }, + { + Keys: opts.GetKeys(opts.Config.Files.CommitChanges), + Handler: self.workingTreeAction(self.c.Helpers().WorkingTree.HandleCommitPress), + Description: self.c.Tr.Commit, + DescriptionFunc: self.workingTreeActionDescription(self.c.Tr.Commit), + Tooltip: self.c.Tr.CommitTooltip, + }, + { + Keys: opts.GetKeys(opts.Config.Files.CommitChangesWithoutHook), + Handler: self.workingTreeAction(self.c.Helpers().WorkingTree.HandleWIPCommitPress), + Description: self.c.Tr.CommitChangesWithoutHook, + DescriptionFunc: self.workingTreeActionDescription(self.c.Tr.CommitChangesWithoutHook), + }, + { + Keys: opts.GetKeys(opts.Config.Files.CommitChangesWithEditor), + Handler: self.workingTreeAction(self.c.Helpers().WorkingTree.HandleCommitEditorPress), + Description: self.c.Tr.CommitChangesWithEditor, + DescriptionFunc: self.workingTreeActionDescription(self.c.Tr.CommitChangesWithEditor), + }, + { + Keys: opts.GetKeys(opts.Config.Files.FindBaseCommitForFixup), + Handler: self.workingTreeAction(self.c.Helpers().FixupHelper.HandleFindBaseCommitForFixupPress), + Description: self.c.Tr.FindBaseCommitForFixup, + DescriptionFunc: self.workingTreeActionDescription(self.c.Tr.FindBaseCommitForFixup), + Tooltip: self.c.Tr.FindBaseCommitForFixupTooltip, + }, {Tag: "navigation", Keys: opts.GetKeys(opts.Config.Universal.PrevPage), Handler: self.handlePrevPage, Description: self.c.Tr.PrevPage}, {Tag: "navigation", Keys: opts.GetKeys(opts.Config.Universal.NextPage), Handler: self.handleNextPage, Description: self.c.Tr.NextPage}, {Tag: "navigation", Keys: opts.GetKeys(opts.Config.Universal.GotoTop), Handler: self.handleGotoTop, Description: self.c.Tr.GotoTop}, @@ -365,6 +391,20 @@ func (self *MainViewController) discardSelection() error { return actions.DiscardSelection(self.context, first, last) } +// workingTreeAction wraps a command that acts on the working tree — committing, finding +// the commit to fix up — so that it only runs while the focused main view is showing the +// working tree's diff. Over a commit's diff the key does nothing, so that browsing +// through history can't commit by accident. The check is per press, since what the main +// view shows changes as the user moves around while the keybindings are registered once. +func (self *MainViewController) workingTreeAction(action func() error) func() error { + return func() error { + if self.diffMainViewType() != types.DiffMainViewTypeStaging { + return nil + } + return action() + } +} + // workingTreeActionDescription gives a command's description only where the command // applies — over the working tree's diff — so that it is listed there and nowhere else. func (self *MainViewController) workingTreeActionDescription(description string) func() string { diff --git a/pkg/integration/tests/main_view/commit_from_main_view.go b/pkg/integration/tests/main_view/commit_from_main_view.go new file mode 100644 index 000000000..fc56ddaf9 --- /dev/null +++ b/pkg/integration/tests/main_view/commit_from_main_view.go @@ -0,0 +1,67 @@ +package main_view + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var CommitFromMainView = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Commit what you staged without leaving the focused main view, but not while looking at a commit's diff", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInStagingView = false + }, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("file1", "one\ntwo\nthree\n") + shell.Commit("one") + + shell.UpdateFile("file1", "one\nADDED\ntwo\nthree\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + // Committing acts on the working tree, so it is offered over the working tree's + // diff and does nothing over a commit's. + t.Views().Commits(). + Focus(). + Press(keys.Universal.FocusMainView) + + t.Views().Main(). + IsFocused(). + Press(keys.Files.CommitChanges). + // Nothing happened: the commit message panel would have taken the focus. + IsFocused() + + t.Views().Files(). + Focus(). + Press(keys.Universal.FocusMainView) + + t.Views().Main(). + IsFocused(). + SelectedLines( + Contains("+ADDED"), + ). + PressPrimaryAction() + + // Staging it left nothing unstaged, so the diff — and the focus with it — is in + // the pane the staged side has. + t.Views().Secondary(). + IsFocused(). + Press(keys.Files.CommitChanges) + + t.ExpectPopup().CommitMessagePanel(). + Type("staged from the diff"). + Confirm() + + // The commit left the staged side with nothing in it, so the pane it was made + // from is gone and the focus is in the one that is still there. + t.Views().Secondary().IsInvisible() + t.Views().Main(). + IsFocused(). + Content(Contains("No changed files")) + + t.Views().Commits().Lines( + Contains("staged from the diff"), + Contains("one"), + ) + }, +}) diff --git a/pkg/integration/tests/test_list.go b/pkg/integration/tests/test_list.go index 50efa3102..79f42c278 100644 --- a/pkg/integration/tests/test_list.go +++ b/pkg/integration/tests/test_list.go @@ -368,6 +368,7 @@ var tests = []*components.IntegrationTest{ interactive_rebase.SwapWithConflict, interactive_rebase.ViewFilesOfTodoEntries, main_view.ClickSelectsDiffLine, + main_view.CommitFromMainView, main_view.CopyRowsThatAreNoDiffLine, main_view.CopySelectedDiffLines, main_view.DiscardDiffLines, From c9c6d00a4730a5cb7e47eb74a743233451273c82 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Sun, 16 Aug 2026 07:54:09 +0200 Subject: [PATCH 13/21] Say what a diff command's output is for MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two things about a diff command follow from what its output is for: whether the diff renderer produces it, and whether it is coloured. That was a `plain` flag, which covers two of the three cases — the diff as configured, and git's own uncoloured diff for building patches out of — and leaves no room for the third, which is about to be needed: git's own diff, coloured, for showing where the renderer's version of it can't be acted on. So the flag becomes a mode. It also takes over deciding the colour, which each command spelled out for itself, and it settles a question the flag couldn't put: whether ignoring whitespace applies. It is about what the user wants to see, so it holds for anything shown, and not for a diff a patch is built from, which has to describe every change. Co-authored-by: Claude Opus 5 (1M context) --- pkg/commands/git.go | 6 ++-- pkg/commands/git_commands/commit.go | 6 ++-- pkg/commands/git_commands/commit_test.go | 2 +- pkg/commands/git_commands/diff.go | 6 ++-- pkg/commands/git_commands/diff_mode.go | 35 +++++++++++++++++++ .../git_commands/git_command_builder.go | 13 ++++--- pkg/commands/git_commands/stash.go | 6 ++-- pkg/commands/git_commands/stash_test.go | 2 +- pkg/commands/git_commands/working_tree.go | 30 ++++++---------- .../git_commands/working_tree_test.go | 30 ++++++++-------- pkg/commands/patch/patch_builder.go | 4 +-- .../controllers/commits_files_controller.go | 4 +-- pkg/gui/controllers/files_controller.go | 6 ++-- pkg/gui/controllers/helpers/diff_helper.go | 8 ++--- .../helpers/patch_building_helper.go | 4 ++- pkg/gui/controllers/helpers/staging_helper.go | 5 +-- .../controllers/reflog_commits_controller.go | 3 +- pkg/gui/controllers/stash_controller.go | 4 ++- pkg/gui/controllers/submodules_controller.go | 4 ++- .../controllers/working_tree_diff_actions.go | 4 +-- pkg/gui/presentation/files_test.go | 2 +- 21 files changed, 112 insertions(+), 72 deletions(-) create mode 100644 pkg/commands/git_commands/diff_mode.go diff --git a/pkg/commands/git.go b/pkg/commands/git.go index 5904dfe4d..bfe19b85f 100644 --- a/pkg/commands/git.go +++ b/pkg/commands/git.go @@ -135,8 +135,10 @@ func NewGitCommandAux( rebaseCommands := git_commands.NewRebaseCommands(gitCommon, commitCommands, workingTreeCommands) stashCommands := git_commands.NewStashCommands(gitCommon, fileLoader, workingTreeCommands) patchBuilder := patch.NewPatchBuilder(cmn.Log, - func(from string, to string, reverse bool, filename string, previousPath string, plain bool) (string, error) { - return workingTreeCommands.ShowFileDiff(from, to, reverse, filename, previousPath, plain) + func(from string, to string, reverse bool, filename string, previousPath string) (string, error) { + // A patch is built from git's own diff: what a diff renderer would make of it + // is a picture of it, not something that can be applied. + return workingTreeCommands.ShowFileDiff(from, to, reverse, filename, previousPath, git_commands.DiffModePlain) }) patchCommands := git_commands.NewPatchCommands(gitCommon, rebaseCommands, commitCommands, statusCommands, stashCommands, patchBuilder) bisectCommands := git_commands.NewBisectCommands(gitCommon) diff --git a/pkg/commands/git_commands/commit.go b/pkg/commands/git_commands/commit.go index d067e9831..387a1fdc7 100644 --- a/pkg/commands/git_commands/commit.go +++ b/pkg/commands/git_commands/commit.go @@ -240,12 +240,12 @@ func (self *CommitCommands) AmendHeadCmdObj() *oscommands.CmdObj { return self.cmd.New(cmdArgs) } -func (self *CommitCommands) ShowCmdObj(hash string, filterPaths []string) *oscommands.CmdObj { +func (self *CommitCommands) ShowCmdObj(hash string, filterPaths []string, mode DiffMode) *oscommands.CmdObj { cmdArgs := NewGitCmd("show"). Config("diff.noprefix=false"). - AddCommonDiffArgs(self.diffRendererConfigManager, self.UserConfig(), true). + AddCommonDiffArgs(self.diffRendererConfigManager, self.UserConfig(), mode). Arg("--submodule"). - Arg("--color=" + self.diffRendererConfigManager.GetColorArg()). + Arg("--color=" + mode.colorArg(self.diffRendererConfigManager)). Arg("--stat"). Arg("--decorate"). Arg("-p"). diff --git a/pkg/commands/git_commands/commit_test.go b/pkg/commands/git_commands/commit_test.go index 4381ccb5f..274385f53 100644 --- a/pkg/commands/git_commands/commit_test.go +++ b/pkg/commands/git_commands/commit_test.go @@ -341,7 +341,7 @@ func TestCommitShowCmdObj(t *testing.T) { } instance := buildCommitCommands(commonDeps{userConfig: userConfig, appState: &config.AppState{}, runner: runner, repoPaths: &repoPaths}) - assert.NoError(t, instance.ShowCmdObj("1234567890", s.filterPaths).Run()) + assert.NoError(t, instance.ShowCmdObj("1234567890", s.filterPaths, DiffModeRendered).Run()) runner.CheckForMissingCalls() }) } diff --git a/pkg/commands/git_commands/diff.go b/pkg/commands/git_commands/diff.go index d532f1bbb..daf710eaa 100644 --- a/pkg/commands/git_commands/diff.go +++ b/pkg/commands/git_commands/diff.go @@ -18,13 +18,13 @@ func NewDiffCommands(gitCommon *GitCommon) *DiffCommands { // This is for generating diffs to be shown in the UI (e.g. rendering a range // diff to the main view). It uses a custom diff renderer if one is configured. -func (self *DiffCommands) DiffCmdObj(diffArgs []string) *oscommands.CmdObj { +func (self *DiffCommands) DiffCmdObj(diffArgs []string, mode DiffMode) *oscommands.CmdObj { return self.cmd.New( NewGitCmd("diff"). Config("diff.noprefix=false"). - AddCommonDiffArgs(self.diffRendererConfigManager, self.UserConfig(), true). + AddCommonDiffArgs(self.diffRendererConfigManager, self.UserConfig(), mode). Arg("--submodule"). - Arg(fmt.Sprintf("--color=%s", self.diffRendererConfigManager.GetColorArg())). + Arg(fmt.Sprintf("--color=%s", mode.colorArg(self.diffRendererConfigManager))). Arg(diffArgs...). Dir(self.repoPaths.worktreePath). ToArgv(), diff --git a/pkg/commands/git_commands/diff_mode.go b/pkg/commands/git_commands/diff_mode.go new file mode 100644 index 000000000..ed3724ef1 --- /dev/null +++ b/pkg/commands/git_commands/diff_mode.go @@ -0,0 +1,35 @@ +package git_commands + +import ( + "github.com/jesseduffield/lazygit/pkg/config" +) + +// DiffMode says what a diff command's output is for. This decides whether the +// configured diff renderer produces it, and whether it is coloured. +type DiffMode int + +const ( + // DiffModeRendered is the diff as the user has arranged for it to look: through the + // diff renderer, with the renderer's own arguments and its preference about colour. + DiffModeRendered DiffMode = iota + // DiffModeRaw is git's own coloured diff, for showing a diff whose rendered form + // couldn't be acted on. + DiffModeRaw + // DiffModePlain is git's own uncoloured diff, for building patches from and copying + // text out of rather than for looking at. + DiffModePlain +) + +// colorArg returns the value to pass to git's --color for this mode. Rendered output is +// coloured however the renderer wants its input; a raw diff gets git's own colour, which +// is the point of it; a plain one is for reading as text, not for looking at. +func (self DiffMode) colorArg(diffRendererConfigManager *config.DiffRendererConfigManager) string { + switch self { + case DiffModeRendered: + return diffRendererConfigManager.GetColorArg() + case DiffModeRaw: + return "always" + default: + return "never" + } +} diff --git a/pkg/commands/git_commands/git_command_builder.go b/pkg/commands/git_commands/git_command_builder.go index 683d46a6f..fe7a6d075 100644 --- a/pkg/commands/git_commands/git_command_builder.go +++ b/pkg/commands/git_commands/git_command_builder.go @@ -123,16 +123,21 @@ func (self *GitCommandBuilder) GitDirIf(condition bool, path string) *GitCommand return self } -func (self *GitCommandBuilder) AddCommonDiffArgs(diffRendererConfigManager *config.DiffRendererConfigManager, userConfig *config.UserConfig, forUI bool) *GitCommandBuilder { +func (self *GitCommandBuilder) AddCommonDiffArgs(diffRendererConfigManager *config.DiffRendererConfigManager, userConfig *config.UserConfig, mode DiffMode) *GitCommandBuilder { contextSize := userConfig.Git.DiffContextSize - useExtDiff := forUI && diffRendererConfigManager.GetDiffRendererType() == config.DiffRendererType_ExtDiff + useExtDiff := mode == DiffModeRendered && diffRendererConfigManager.GetDiffRendererType() == config.DiffRendererType_ExtDiff return self. ArgIfElse(useExtDiff, "--ext-diff", "--no-ext-diff"). Arg(fmt.Sprintf("--unified=%d", contextSize)). - ArgIf(forUI && userConfig.Git.IgnoreWhitespaceInDiffView, "--ignore-all-space"). + // Ignoring whitespace is about what the user wants to see, so it holds for a raw + // diff as much as for a rendered one. Patches are built from a plain diff, + // where a diff that leaves changes out would apply to nothing. + ArgIf(mode != DiffModePlain && userConfig.Git.IgnoreWhitespaceInDiffView, "--ignore-all-space"). Arg(fmt.Sprintf("--find-renames=%d%%", userConfig.Git.RenameSimilarityThreshold)). - ArgIf(forUI, diffRendererConfigManager.GetRawGitArgs()...) + // The renderer's own arguments to git — a word diff, say — are part of the + // rendering, so they go with it. + ArgIf(mode == DiffModeRendered, diffRendererConfigManager.GetRawGitArgs()...) } func (self *GitCommandBuilder) ToArgv() []string { diff --git a/pkg/commands/git_commands/stash.go b/pkg/commands/git_commands/stash.go index ea23c5141..f904a7ac4 100644 --- a/pkg/commands/git_commands/stash.go +++ b/pkg/commands/git_commands/stash.go @@ -80,14 +80,14 @@ func (self *StashCommands) Hash(index int) (string, error) { return strings.Trim(hash, "\r\n"), err } -func (self *StashCommands) ShowStashEntryCmdObj(index int) *oscommands.CmdObj { +func (self *StashCommands) ShowStashEntryCmdObj(index int, mode DiffMode) *oscommands.CmdObj { // "-u" is the same as "--include-untracked", but the latter fails in older git versions for some reason cmdArgs := NewGitCmd("stash").Arg("show"). - AddCommonDiffArgs(self.diffRendererConfigManager, self.UserConfig(), true). + AddCommonDiffArgs(self.diffRendererConfigManager, self.UserConfig(), mode). Arg("-p"). Arg("--stat"). Arg("-u"). - Arg(fmt.Sprintf("--color=%s", self.diffRendererConfigManager.GetColorArg())). + Arg(fmt.Sprintf("--color=%s", mode.colorArg(self.diffRendererConfigManager))). Arg(fmt.Sprintf("refs/stash@{%d}", index)). Dir(self.repoPaths.worktreePath). ToArgv() diff --git a/pkg/commands/git_commands/stash_test.go b/pkg/commands/git_commands/stash_test.go index 91eb846ed..35b687cbd 100644 --- a/pkg/commands/git_commands/stash_test.go +++ b/pkg/commands/git_commands/stash_test.go @@ -174,7 +174,7 @@ func TestStashStashEntryCmdObj(t *testing.T) { } instance := buildStashCommands(commonDeps{userConfig: userConfig, appState: &config.AppState{}, repoPaths: &repoPaths}) - cmdStr := instance.ShowStashEntryCmdObj(s.index).Args() + cmdStr := instance.ShowStashEntryCmdObj(s.index, DiffModeRendered).Args() assert.Equal(t, s.expected, cmdStr) }) } diff --git a/pkg/commands/git_commands/working_tree.go b/pkg/commands/git_commands/working_tree.go index 1ab37fa6a..4f4a19a89 100644 --- a/pkg/commands/git_commands/working_tree.go +++ b/pkg/commands/git_commands/working_tree.go @@ -383,9 +383,9 @@ func (self *WorkingTreeCommands) Exclude(filename string) error { } // WorktreeFileDiff returns the diff of a file -func (self *WorkingTreeCommands) WorktreeFileDiff(file *models.File, plain bool, cached bool) string { +func (self *WorkingTreeCommands) WorktreeFileDiff(file *models.File, mode DiffMode, cached bool) string { // for now we assume an error means the file was deleted - s, _ := self.WorktreeFileDiffCmdObj(file, plain, cached, file.Names()).RunWithOutput() + s, _ := self.WorktreeFileDiffCmdObj(file, mode, cached, file.Names()).RunWithOutput() return s } @@ -393,18 +393,13 @@ func (self *WorkingTreeCommands) WorktreeFileDiff(file *models.File, plain bool, // in the working tree. node is the item they belong to; all it decides is // whether git has to compare against /dev/null, which is the case for a file // that isn't in the index yet. -func (self *WorkingTreeCommands) WorktreeFileDiffCmdObj(node models.IFile, plain bool, cached bool, paths []string) *oscommands.CmdObj { - colorArg := self.diffRendererConfigManager.GetColorArg() - if plain { - colorArg = "never" - } - +func (self *WorkingTreeCommands) WorktreeFileDiffCmdObj(node models.IFile, mode DiffMode, cached bool, paths []string) *oscommands.CmdObj { noIndex := !node.GetIsTracked() && !node.GetHasStagedChanges() && !cached && node.GetIsFile() cmdArgs := NewGitCmd("diff"). - AddCommonDiffArgs(self.diffRendererConfigManager, self.UserConfig(), !plain). + AddCommonDiffArgs(self.diffRendererConfigManager, self.UserConfig(), mode). Arg("--submodule"). - Arg(fmt.Sprintf("--color=%s", colorArg)). + Arg(fmt.Sprintf("--color=%s", mode.colorArg(self.diffRendererConfigManager))). ArgIf(cached, "--cached"). ArgIf(noIndex, "--no-index"). Arg("--"). @@ -420,25 +415,20 @@ func (self *WorkingTreeCommands) WorktreeFileDiffCmdObj(node models.IFile, plain // but when we're in diff mode it could be any 'from' to any 'to'. The reverse flag is also here thanks to diff mode. // For a renamed file, previousPath is the path it was renamed from (empty otherwise); // both paths must be passed to git for the rename to be detected. -func (self *WorkingTreeCommands) ShowFileDiff(from string, to string, reverse bool, fileName string, previousPath string, plain bool) (string, error) { +func (self *WorkingTreeCommands) ShowFileDiff(from string, to string, reverse bool, fileName string, previousPath string, mode DiffMode) (string, error) { fileNames := []string{fileName} if previousPath != "" { fileNames = append(fileNames, previousPath) } - return self.ShowFileDiffCmdObj(from, to, reverse, fileNames, plain).RunWithOutput() + return self.ShowFileDiffCmdObj(from, to, reverse, fileNames, mode).RunWithOutput() } -func (self *WorkingTreeCommands) ShowFileDiffCmdObj(from string, to string, reverse bool, fileNames []string, plain bool) *oscommands.CmdObj { - colorArg := self.diffRendererConfigManager.GetColorArg() - if plain { - colorArg = "never" - } - +func (self *WorkingTreeCommands) ShowFileDiffCmdObj(from string, to string, reverse bool, fileNames []string, mode DiffMode) *oscommands.CmdObj { cmdArgs := NewGitCmd("diff"). Config("diff.noprefix=false"). - AddCommonDiffArgs(self.diffRendererConfigManager, self.UserConfig(), !plain). + AddCommonDiffArgs(self.diffRendererConfigManager, self.UserConfig(), mode). Arg("--submodule"). - Arg(fmt.Sprintf("--color=%s", colorArg)). + Arg(fmt.Sprintf("--color=%s", mode.colorArg(self.diffRendererConfigManager))). Arg(from). Arg(to). ArgIf(reverse, "-R"). diff --git a/pkg/commands/git_commands/working_tree_test.go b/pkg/commands/git_commands/working_tree_test.go index 5b87a1320..e9e5e48d2 100644 --- a/pkg/commands/git_commands/working_tree_test.go +++ b/pkg/commands/git_commands/working_tree_test.go @@ -197,7 +197,7 @@ func TestWorkingTreeDiff(t *testing.T) { type scenario struct { testName string file *models.File - plain bool + mode DiffMode cached bool ignoreWhitespace bool contextSize uint64 @@ -215,7 +215,7 @@ func TestWorkingTreeDiff(t *testing.T) { HasStagedChanges: false, Tracked: true, }, - plain: false, + mode: DiffModeRendered, cached: false, ignoreWhitespace: false, contextSize: 3, @@ -230,7 +230,7 @@ func TestWorkingTreeDiff(t *testing.T) { HasStagedChanges: false, Tracked: true, }, - plain: false, + mode: DiffModeRendered, cached: true, ignoreWhitespace: false, contextSize: 3, @@ -245,7 +245,7 @@ func TestWorkingTreeDiff(t *testing.T) { HasStagedChanges: false, Tracked: true, }, - plain: true, + mode: DiffModePlain, cached: false, ignoreWhitespace: false, contextSize: 3, @@ -260,7 +260,7 @@ func TestWorkingTreeDiff(t *testing.T) { HasStagedChanges: false, Tracked: false, }, - plain: false, + mode: DiffModeRendered, cached: false, ignoreWhitespace: false, contextSize: 3, @@ -275,7 +275,7 @@ func TestWorkingTreeDiff(t *testing.T) { HasStagedChanges: false, Tracked: true, }, - plain: false, + mode: DiffModeRendered, cached: false, ignoreWhitespace: true, contextSize: 3, @@ -290,7 +290,7 @@ func TestWorkingTreeDiff(t *testing.T) { HasStagedChanges: false, Tracked: true, }, - plain: false, + mode: DiffModeRendered, cached: false, ignoreWhitespace: false, contextSize: 17, @@ -305,7 +305,7 @@ func TestWorkingTreeDiff(t *testing.T) { HasStagedChanges: false, Tracked: true, }, - plain: false, + mode: DiffModeRendered, cached: false, ignoreWhitespace: false, contextSize: 3, @@ -326,7 +326,7 @@ func TestWorkingTreeDiff(t *testing.T) { } instance := buildWorkingTreeCommands(commonDeps{runner: s.runner, userConfig: userConfig, appState: &config.AppState{}, repoPaths: &repoPaths}) - result := instance.WorktreeFileDiff(s.file, s.plain, s.cached) + result := instance.WorktreeFileDiff(s.file, s.mode, s.cached) assert.Equal(t, expectedResult, result) s.runner.CheckForMissingCalls() }) @@ -341,7 +341,7 @@ func TestWorkingTreeShowFileDiff(t *testing.T) { reverse bool fileName string previousPath string - plain bool + mode DiffMode ignoreWhitespace bool contextSize uint64 runner *oscommands.FakeCmdObjRunner @@ -356,7 +356,7 @@ func TestWorkingTreeShowFileDiff(t *testing.T) { to: "0987654321", reverse: false, fileName: "test.txt", - plain: false, + mode: DiffModeRendered, ignoreWhitespace: false, contextSize: 3, runner: oscommands.NewFakeRunner(t). @@ -368,7 +368,7 @@ func TestWorkingTreeShowFileDiff(t *testing.T) { to: "0987654321", reverse: false, fileName: "test.txt", - plain: false, + mode: DiffModeRendered, ignoreWhitespace: false, contextSize: 123, runner: oscommands.NewFakeRunner(t). @@ -380,7 +380,7 @@ func TestWorkingTreeShowFileDiff(t *testing.T) { to: "0987654321", reverse: false, fileName: "test.txt", - plain: false, + mode: DiffModeRendered, ignoreWhitespace: true, contextSize: 3, runner: oscommands.NewFakeRunner(t). @@ -393,7 +393,7 @@ func TestWorkingTreeShowFileDiff(t *testing.T) { reverse: false, fileName: "new.txt", previousPath: "old.txt", - plain: false, + mode: DiffModeRendered, ignoreWhitespace: false, contextSize: 3, runner: oscommands.NewFakeRunner(t). @@ -412,7 +412,7 @@ func TestWorkingTreeShowFileDiff(t *testing.T) { instance := buildWorkingTreeCommands(commonDeps{runner: s.runner, userConfig: userConfig, appState: &config.AppState{}, repoPaths: &repoPaths}) - result, err := instance.ShowFileDiff(s.from, s.to, s.reverse, s.fileName, s.previousPath, s.plain) + result, err := instance.ShowFileDiff(s.from, s.to, s.reverse, s.fileName, s.previousPath, s.mode) assert.NoError(t, err) assert.Equal(t, expectedResult, result) s.runner.CheckForMissingCalls() diff --git a/pkg/commands/patch/patch_builder.go b/pkg/commands/patch/patch_builder.go index 0d5ca34f8..78c539e86 100644 --- a/pkg/commands/patch/patch_builder.go +++ b/pkg/commands/patch/patch_builder.go @@ -33,7 +33,7 @@ type fileInfo struct { } type ( - loadFileDiffFunc func(from string, to string, reverse bool, filename string, previousPath string, plain bool) (string, error) + loadFileDiffFunc func(from string, to string, reverse bool, filename string, previousPath string) (string, error) ) // PatchBuilder manages the building of a patch for a commit to be applied to another commit (or the working tree, or removed from the current commit). We also support building patches from things like stashes, for which there is less flexibility @@ -162,7 +162,7 @@ func (p *PatchBuilder) getFileInfo(filename string, previousPath string) (*fileI return info, nil } - diff, err := p.loadFileDiff(from, to, reverse, filename, previousPath, true) + diff, err := p.loadFileDiff(from, to, reverse, filename, previousPath) if err != nil { return nil, err } diff --git a/pkg/gui/controllers/commits_files_controller.go b/pkg/gui/controllers/commits_files_controller.go index 2e31ad906..f59056da1 100644 --- a/pkg/gui/controllers/commits_files_controller.go +++ b/pkg/gui/controllers/commits_files_controller.go @@ -176,7 +176,7 @@ func (self *CommitFilesController) GetOnRenderToMain() func() { from, reverse := self.c.Modes().Diffing.GetFromAndReverseArgsForDiff(from) paths := self.pathsForDiff(node) - cmdObj := self.c.Git().WorkingTree.ShowFileDiffCmdObj(from, to, reverse, paths, false) + cmdObj := self.c.Git().WorkingTree.ShowFileDiffCmdObj(from, to, reverse, paths, git_commands.DiffModeRendered) task := types.NewRunDiffRendererTask(cmdObj.GetCmd()) self.c.RenderToMainViews(types.RefreshMainOpts{ @@ -207,7 +207,7 @@ func (self *CommitFilesController) copyDiffToClipboard(paths []string, toastMess from, to := self.context().GetFromAndToForDiff() from, reverse := self.c.Modes().Diffing.GetFromAndReverseArgsForDiff(from) - cmdObj := self.c.Git().WorkingTree.ShowFileDiffCmdObj(from, to, reverse, paths, true) + cmdObj := self.c.Git().WorkingTree.ShowFileDiffCmdObj(from, to, reverse, paths, git_commands.DiffModePlain) diff, err := cmdObj.RunWithOutput() if err != nil { return err diff --git a/pkg/gui/controllers/files_controller.go b/pkg/gui/controllers/files_controller.go index 93bc6f379..2b9f37064 100644 --- a/pkg/gui/controllers/files_controller.go +++ b/pkg/gui/controllers/files_controller.go @@ -352,7 +352,7 @@ func (self *FilesController) renderNonTextualConflict(node *filetree.FileNode) { message := self.conflictResolutionHint(node.File.GetMergeStateDescription(self.c.Tr)) if node.File.ShortStatus == "DU" || node.File.ShortStatus == "UD" { - cmdObj := self.c.Git().Diff.DiffCmdObj([]string{"--base", "--", node.GetPath()}) + cmdObj := self.c.Git().Diff.DiffCmdObj([]string{"--base", "--", node.GetPath()}, git_commands.DiffModeRendered) prefix := message + "\n\n" if node.File.ShortStatus == "DU" { prefix += self.c.Tr.MergeConflictIncomingDiff @@ -384,7 +384,7 @@ func (self *FilesController) renderWorkingTreeDiff(node *filetree.FileNode) { refreshOpts := types.RefreshMainOpts{Pair: self.c.MainViewPairs().Normal} if showUnstaged { - cmdObj := self.c.Git().WorkingTree.WorktreeFileDiffCmdObj(node, false, false, paths) + cmdObj := self.c.Git().WorkingTree.WorktreeFileDiffCmdObj(node, git_commands.DiffModeRendered, false, paths) refreshOpts.Main = &types.ViewUpdateOpts{ Task: types.NewRunDiffRendererTask(cmdObj.GetCmd()), SubTitle: self.c.Helpers().Diff.IgnoringWhitespaceSubTitle(), @@ -394,7 +394,7 @@ func (self *FilesController) renderWorkingTreeDiff(node *filetree.FileNode) { } if showStaged { - cmdObj := self.c.Git().WorkingTree.WorktreeFileDiffCmdObj(node, false, true, paths) + cmdObj := self.c.Git().WorkingTree.WorktreeFileDiffCmdObj(node, git_commands.DiffModeRendered, true, paths) refreshOpts.Secondary = &types.ViewUpdateOpts{ Task: types.NewRunDiffRendererTask(cmdObj.GetCmd()), SubTitle: self.c.Helpers().Diff.IgnoringWhitespaceSubTitle(), diff --git a/pkg/gui/controllers/helpers/diff_helper.go b/pkg/gui/controllers/helpers/diff_helper.go index c5d88f39b..3a8306fc2 100644 --- a/pkg/gui/controllers/helpers/diff_helper.go +++ b/pkg/gui/controllers/helpers/diff_helper.go @@ -74,12 +74,12 @@ func (self *DiffHelper) GetUpdateTaskForRenderingCommitsDiff(commit *models.Comm args = append(args, filterPath) } } - cmdObj := self.c.Git().Diff.DiffCmdObj(args) + cmdObj := self.c.Git().Diff.DiffCmdObj(args, git_commands.DiffModeRendered) prefix := style.FgYellow.Sprintf("%s %s-%s\n\n", self.c.Tr.ShowingDiffForRange, from.ShortRefName(), to.ShortRefName()) return types.NewRunDiffRendererTaskWithPrefix(cmdObj.GetCmd(), prefix) } - cmdObj := self.c.Git().Commit.ShowCmdObj(commit.Hash(), self.FilterPathsForCommit(commit)) + cmdObj := self.c.Git().Commit.ShowCmdObj(commit.Hash(), self.FilterPathsForCommit(commit), git_commands.DiffModeRendered) return types.NewRunDiffRendererTask(cmdObj.GetCmd()) } @@ -92,7 +92,7 @@ func (self *DiffHelper) PlainDiffBetweenRefs(from string, to string, paths []str from, reverse := self.c.Modes().Diffing.GetFromAndReverseArgsForDiff(from) // An error means there is no diff to be had, which for our purposes is the same // as an empty one. - diff, _ := self.c.Git().WorkingTree.ShowFileDiffCmdObj(from, to, reverse, paths, true).RunWithOutput() + diff, _ := self.c.Git().WorkingTree.ShowFileDiffCmdObj(from, to, reverse, paths, git_commands.DiffModePlain).RunWithOutput() return diff } @@ -133,7 +133,7 @@ func (self *DiffHelper) RenderToMainAgain() { func (self *DiffHelper) RenderDiff() { args := self.DiffArgs() - cmdObj := self.c.Git().Diff.DiffCmdObj(args) + cmdObj := self.c.Git().Diff.DiffCmdObj(args, git_commands.DiffModeRendered) prefix := style.FgMagenta.Sprintf( "%s %s\n\n", self.c.Tr.ShowingGitDiff, diff --git a/pkg/gui/controllers/helpers/patch_building_helper.go b/pkg/gui/controllers/helpers/patch_building_helper.go index ac79ee8d7..d8288df4f 100644 --- a/pkg/gui/controllers/helpers/patch_building_helper.go +++ b/pkg/gui/controllers/helpers/patch_building_helper.go @@ -3,6 +3,8 @@ package helpers import ( "fmt" + "github.com/jesseduffield/lazygit/pkg/commands/git_commands" + "github.com/jesseduffield/lazygit/pkg/commands/patch" "github.com/jesseduffield/lazygit/pkg/gui/patch_exploring" "github.com/jesseduffield/lazygit/pkg/gui/types" @@ -73,7 +75,7 @@ func (self *PatchBuildingHelper) RefreshPatchBuildingPanel(opts types.OnFocusOpt from, to := self.c.Contexts().CommitFiles.GetFromAndToForDiff() from, reverse := self.c.Modes().Diffing.GetFromAndReverseArgsForDiff(from) - diff, err := self.c.Git().WorkingTree.ShowFileDiff(from, to, reverse, file.Path, file.PreviousPath, true) + diff, err := self.c.Git().WorkingTree.ShowFileDiff(from, to, reverse, file.Path, file.PreviousPath, git_commands.DiffModePlain) if err != nil { return } diff --git a/pkg/gui/controllers/helpers/staging_helper.go b/pkg/gui/controllers/helpers/staging_helper.go index 55b9c133b..071c1d4be 100644 --- a/pkg/gui/controllers/helpers/staging_helper.go +++ b/pkg/gui/controllers/helpers/staging_helper.go @@ -1,6 +1,7 @@ package helpers import ( + "github.com/jesseduffield/lazygit/pkg/commands/git_commands" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/patch_exploring" "github.com/jesseduffield/lazygit/pkg/gui/types" @@ -53,8 +54,8 @@ func (self *StagingHelper) RefreshStagingPanel(focusOpts types.OnFocusOpts) { return } - mainDiff := self.c.Git().WorkingTree.WorktreeFileDiff(file, true, false) - secondaryDiff := self.c.Git().WorkingTree.WorktreeFileDiff(file, true, true) + mainDiff := self.c.Git().WorkingTree.WorktreeFileDiff(file, git_commands.DiffModePlain, false) + secondaryDiff := self.c.Git().WorkingTree.WorktreeFileDiff(file, git_commands.DiffModePlain, true) // grabbing locks here and releasing before we finish the function // because pushing say the secondary context could mean entering this function diff --git a/pkg/gui/controllers/reflog_commits_controller.go b/pkg/gui/controllers/reflog_commits_controller.go index a0a008105..bd000214f 100644 --- a/pkg/gui/controllers/reflog_commits_controller.go +++ b/pkg/gui/controllers/reflog_commits_controller.go @@ -1,6 +1,7 @@ package controllers import ( + "github.com/jesseduffield/lazygit/pkg/commands/git_commands" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/types" @@ -59,7 +60,7 @@ func (self *ReflogCommitsController) GetOnRenderToMain() func() { if commit == nil { task = types.NewRenderStringTask("No reflog history") } else { - cmdObj := self.c.Git().Commit.ShowCmdObj(commit.Hash(), self.c.Helpers().Diff.FilterPathsForCommit(commit)) + cmdObj := self.c.Git().Commit.ShowCmdObj(commit.Hash(), self.c.Helpers().Diff.FilterPathsForCommit(commit), git_commands.DiffModeRendered) task = types.NewRunDiffRendererTask(cmdObj.GetCmd()) } diff --git a/pkg/gui/controllers/stash_controller.go b/pkg/gui/controllers/stash_controller.go index 79a2bcd20..762090ae6 100644 --- a/pkg/gui/controllers/stash_controller.go +++ b/pkg/gui/controllers/stash_controller.go @@ -3,6 +3,8 @@ package controllers import ( "fmt" + "github.com/jesseduffield/lazygit/pkg/commands/git_commands" + "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gocui" "github.com/jesseduffield/lazygit/pkg/gui/context" @@ -94,7 +96,7 @@ func (self *StashController) GetOnRenderToMain() func() { } else { prefix := style.FgYellow.Sprintf("%s\n\n", stashEntry.Description()) task = types.NewRunDiffRendererTaskWithPrefix( - self.c.Git().Stash.ShowStashEntryCmdObj(stashEntry.Index).GetCmd(), + self.c.Git().Stash.ShowStashEntryCmdObj(stashEntry.Index, git_commands.DiffModeRendered).GetCmd(), prefix, ) } diff --git a/pkg/gui/controllers/submodules_controller.go b/pkg/gui/controllers/submodules_controller.go index 82ca509ca..c807e6352 100644 --- a/pkg/gui/controllers/submodules_controller.go +++ b/pkg/gui/controllers/submodules_controller.go @@ -5,6 +5,8 @@ import ( "path/filepath" "strings" + "github.com/jesseduffield/lazygit/pkg/commands/git_commands" + "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gocui" "github.com/jesseduffield/lazygit/pkg/gui/context" @@ -123,7 +125,7 @@ func (self *SubmodulesController) GetOnRenderToMain() func() { if file == nil { task = types.NewRenderStringTask(prefix) } else { - cmdObj := self.c.Git().WorkingTree.WorktreeFileDiffCmdObj(file, false, !file.HasUnstagedChanges && file.HasStagedChanges, file.Names()) + cmdObj := self.c.Git().WorkingTree.WorktreeFileDiffCmdObj(file, git_commands.DiffModeRendered, !file.HasUnstagedChanges && file.HasStagedChanges, file.Names()) task = types.NewRunCommandTaskWithPrefix(cmdObj.GetCmd(), prefix) } } diff --git a/pkg/gui/controllers/working_tree_diff_actions.go b/pkg/gui/controllers/working_tree_diff_actions.go index 00f3fab1c..8070e0e7e 100644 --- a/pkg/gui/controllers/working_tree_diff_actions.go +++ b/pkg/gui/controllers/working_tree_diff_actions.go @@ -40,7 +40,7 @@ func (self *WorkingTreeDiffActions) PlainDiff(pane types.DiffPaneContext, paths // An error means there is no diff to be had, which for our purposes is the same as // an empty one. diff, _ := self.c.Git().WorkingTree. - WorktreeFileDiffCmdObj(node, true, self.showsStagedSide(pane), paths). + WorktreeFileDiffCmdObj(node, git_commands.DiffModePlain, self.showsStagedSide(pane), paths). RunWithOutput() return diff } @@ -196,7 +196,7 @@ func (self *WorkingTreeDiffActions) fileForDiffLinePath(path string) *models.Fil func (self *WorkingTreeDiffActions) applyDiffLines( file *models.File, infos []types.DiffLineInfo, sourceCached bool, opts git_commands.ApplyPatchOpts, ) (bool, error) { - parsedPatch := patch.Parse(self.c.Git().WorkingTree.WorktreeFileDiff(file, true, sourceCached)) + parsedPatch := patch.Parse(self.c.Git().WorkingTree.WorktreeFileDiff(file, git_commands.DiffModePlain, sourceCached)) type changeLine struct { lineNumber int diff --git a/pkg/gui/presentation/files_test.go b/pkg/gui/presentation/files_test.go index c7e333682..74d8f1369 100644 --- a/pkg/gui/presentation/files_test.go +++ b/pkg/gui/presentation/files_test.go @@ -227,7 +227,7 @@ M file1 } patchBuilder := patch.NewPatchBuilder( utils.NewDummyLog(), - func(from string, to string, reverse bool, filename string, previousPath string, plain bool) (string, error) { + func(from string, to string, reverse bool, filename string, previousPath string) (string, error) { return "", nil }, ) From e85c0cb4199b15ca965e25062ebe04587facc840 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Sun, 16 Aug 2026 08:10:15 +0200 Subject: [PATCH 14/21] Show git's own diff when the renderer's can't be acted on A diff renderer may lay a diff out however it likes: line numbers in a gutter, the +/- column replaced by colour, the two sides in columns. Once it has, we can only tell which line of which file a row shows if the renderer says so. Under a renderer that doesn't say, the main view holds a diff that can be read but not staged, edited or copied from. That is no good now that the main view is where you stage. So focusing it brings git's own diff instead, and every re-render while it stays focused keeps to that, so staging a hunk doesn't flip back. Browsing is untouched: you see what the renderer produced until you focus the view to act on it. Whether the renderer says anything is settled by asking it rather than by watching it work: run it on empty input and see whether it announces the protocol. Announcing is a property of the renderer, so the answer is known before we render anything, and a diff with no lines to describe can't fool it. Watching would have to see a diff go by first, and a binary file's diff holds nothing that would tell the two cases apart. The answer is remembered until the renderer changes. git itself is asked the same question, with the renderer's own arguments, since it announces itself for exactly the formats whose output can't be read back as a diff. Co-authored-by: Claude Opus 5 (1M context) --- pkg/commands/git_commands/diff.go | 125 ++++++++++++++++++ .../controllers/commits_files_controller.go | 5 +- pkg/gui/controllers/files_controller.go | 12 +- pkg/gui/controllers/helpers/diff_helper.go | 10 +- .../controllers/helpers/diff_line_helper.go | 5 + .../helpers/diff_line_raw_fallback.go | 112 ++++++++++++++++ .../controllers/reflog_commits_controller.go | 6 +- pkg/gui/controllers/stash_controller.go | 8 +- .../switch_to_focused_main_view_controller.go | 18 ++- pkg/gui/types/rendering.go | 17 +++ .../main_view/copy_selected_diff_lines.go | 8 +- ..._position_when_switching_diff_renderers.go | 7 +- ...eep_selection_visible_when_diff_shrinks.go | 5 +- .../raw_fallback_under_an_external_diff.go | 63 +++++++++ .../stage_under_conforming_diff_renderer.go | 55 ++++++++ .../stage_under_unsupported_diff_renderer.go | 71 ++++++++++ pkg/integration/tests/test_list.go | 3 + 17 files changed, 504 insertions(+), 26 deletions(-) create mode 100644 pkg/gui/controllers/helpers/diff_line_raw_fallback.go create mode 100644 pkg/integration/tests/main_view/raw_fallback_under_an_external_diff.go create mode 100644 pkg/integration/tests/main_view/stage_under_conforming_diff_renderer.go create mode 100644 pkg/integration/tests/main_view/stage_under_unsupported_diff_renderer.go diff --git a/pkg/commands/git_commands/diff.go b/pkg/commands/git_commands/diff.go index daf710eaa..3fece6235 100644 --- a/pkg/commands/git_commands/diff.go +++ b/pkg/commands/git_commands/diff.go @@ -2,10 +2,135 @@ package git_commands import ( "fmt" + "os" + "strings" "github.com/jesseduffield/lazygit/pkg/commands/oscommands" + "github.com/jesseduffield/lazygit/pkg/config" + "github.com/mgutz/str" ) +// metadataHandshake is the record a diff renderer that speaks the OSC 1717 protocol +// emits before anything else, to announce that it does: a version-only record, with +// none of the fields a line's record has. See ProbeDiffRendererEmitsMetadata, and +// gocui's escape interpreter for how it is kept off the screen on a real render. +const metadataHandshake = "\x1b]1717" + +// probeWidth is the width a probe asks the renderer to lay out to. A probe has +// nothing to render, so any width does, as long as it is one a renderer will +// accept: a renderer that lays its rendering out in columns may well refuse a +// width of zero, and would then never get as far as announcing itself. +const probeWidth = 80 + +// ProbeDiffRendererEmitsMetadata reports whether the configured diff renderer states +// which line of which file it is rendering, by running it on empty input and looking +// for the handshake. The answer decides whether a diff the renderer produced can be +// acted on at all, or has to be replaced by git's own when the user wants to act on it +// (see DiffLineHelper.MainViewDiffMode). +// +// Asking rather than watching a real render: the handshake is the renderer's first +// output whatever the diff, so the answer is a property of the renderer, known before +// we render anything — where watching would have to see a diff go by first, and would +// be fooled by a diff with no lines to describe. +// +// No terminal is needed. git only invokes a stdin filter when it thinks it is talking +// to one, but the renderer itself doesn't care: it announces itself whenever OSC1717 is +// set, so it can be run directly with empty input. +func (self *DiffCommands) ProbeDiffRendererEmitsMetadata() bool { + manager := self.diffRendererConfigManager + values := config.DiffRendererValues{Width: probeWidth, DiffContext: 3} + + switch manager.GetDiffRendererType() { + case config.DiffRendererType_StdinFilter: + if command, err := manager.GetStdinFilterCommand(values); err == nil && command != "" { + return self.probeEmitsMetadata(self.cmd.NewShell(command, "")) + } + case config.DiffRendererType_ExtDiff: + // An empty command means git's own diff.external config, which picks a driver + // per file through .gitattributes: there is no one renderer to ask, and a single + // diff can be produced by several, so we take it that it says nothing. + if command, err := manager.GetExternalDiffCommand(values); err == nil && command != "" { + return self.externalDiffEmitsMetadata(command) + } + case config.DiffRendererType_RawGit: + // git describes only the formats whose output can't be read back as a diff, and + // asked with the renderer's own arguments it answers for exactly the format + // those select: a handshake for a word diff, silence for a unified one. With no + // arguments there is nothing to fall back to anyway, since this already is git's + // own diff. + if args := manager.GetRawGitArgs(); len(args) > 0 { + return self.rawGitEmitsMetadata(args) + } + } + + return false +} + +// rawGitEmitsMetadata asks git itself, run with the diff renderer's own arguments. +func (self *DiffCommands) rawGitEmitsMetadata(rawGitArgs []string) bool { + oldPath, newPath, cleanup, ok := self.probeFiles() + if !ok { + return false + } + defer cleanup() + + return self.probeEmitsMetadata(self.cmd.New( + NewGitCmd("diff"). + Arg("--no-index"). + Arg(rawGitArgs...). + Arg(oldPath, newPath). + ToArgv(), + )) +} + +// externalDiffEmitsMetadata asks an external diff command, invoking it the way git +// invokes one — with the seven positional arguments of git's diff.external convention — +// over two empty files, so that it announces itself without having a diff to render. +func (self *DiffCommands) externalDiffEmitsMetadata(externalDiffCommand string) bool { + oldPath, newPath, cleanup, ok := self.probeFiles() + if !ok { + return false + } + defer cleanup() + + args := append(str.ToArgv(externalDiffCommand), + "probe", oldPath, "0000000", "100644", newPath, "0000000", "100644") + return self.probeEmitsMetadata(self.cmd.New(args)) +} + +// probeFiles makes the two empty files a probe stands a diff up from, and the cleanup +// that removes them. Empty, because what the probe wants is for the renderer to announce +// itself, not for it to have anything to say. +func (self *DiffCommands) probeFiles() (string, string, func(), bool) { + tempDir := self.os.GetTempDir() + + oldFile, err := os.CreateTemp(tempDir, "lazygit-probe-old-*") + if err != nil { + return "", "", nil, false + } + oldFile.Close() + + newFile, err := os.CreateTemp(tempDir, "lazygit-probe-new-*") + if err != nil { + os.Remove(oldFile.Name()) + return "", "", nil, false + } + newFile.Close() + + return oldFile.Name(), newFile.Name(), func() { + os.Remove(oldFile.Name()) + os.Remove(newFile.Name()) + }, true +} + +func (self *DiffCommands) probeEmitsMetadata(cmdObj *oscommands.CmdObj) bool { + cmdObj.AddEnvVars("OSC1717=V1") + // A renderer may well object to being handed nothing to render. We want to know + // whatever it said before objecting, and that is captured either way. + output, _ := cmdObj.RunWithOutput() + return strings.Contains(output, metadataHandshake) +} + type DiffCommands struct { *GitCommon } diff --git a/pkg/gui/controllers/commits_files_controller.go b/pkg/gui/controllers/commits_files_controller.go index f59056da1..bb197ae73 100644 --- a/pkg/gui/controllers/commits_files_controller.go +++ b/pkg/gui/controllers/commits_files_controller.go @@ -175,9 +175,10 @@ func (self *CommitFilesController) GetOnRenderToMain() func() { from, to := self.context().GetFromAndToForDiff() from, reverse := self.c.Modes().Diffing.GetFromAndReverseArgsForDiff(from) + mode := self.c.Helpers().DiffLine.MainViewDiffMode() paths := self.pathsForDiff(node) - cmdObj := self.c.Git().WorkingTree.ShowFileDiffCmdObj(from, to, reverse, paths, git_commands.DiffModeRendered) - task := types.NewRunDiffRendererTask(cmdObj.GetCmd()) + cmdObj := self.c.Git().WorkingTree.ShowFileDiffCmdObj(from, to, reverse, paths, mode) + task := types.NewMainViewDiffTask(cmdObj.GetCmd(), mode) self.c.RenderToMainViews(types.RefreshMainOpts{ Pair: self.c.MainViewPairs().Normal, diff --git a/pkg/gui/controllers/files_controller.go b/pkg/gui/controllers/files_controller.go index 2b9f37064..2828f8a4d 100644 --- a/pkg/gui/controllers/files_controller.go +++ b/pkg/gui/controllers/files_controller.go @@ -380,13 +380,17 @@ func (self *FilesController) renderWorkingTreeDiff(node *filetree.FileNode) { showStaged := node.GetHasStagedChanges() || alwaysSplit showUnstaged := node.GetHasUnstagedChanges() || alwaysSplit || !showStaged + // While the main view is focused to act on this diff, it may have to be git's own + // rather than the diff renderer's; both panes have to agree about that. + mode := self.c.Helpers().DiffLine.MainViewDiffMode() + paths := self.pathsForDiff(node) refreshOpts := types.RefreshMainOpts{Pair: self.c.MainViewPairs().Normal} if showUnstaged { - cmdObj := self.c.Git().WorkingTree.WorktreeFileDiffCmdObj(node, git_commands.DiffModeRendered, false, paths) + cmdObj := self.c.Git().WorkingTree.WorktreeFileDiffCmdObj(node, mode, false, paths) refreshOpts.Main = &types.ViewUpdateOpts{ - Task: types.NewRunDiffRendererTask(cmdObj.GetCmd()), + Task: types.NewMainViewDiffTask(cmdObj.GetCmd(), mode), SubTitle: self.c.Helpers().Diff.IgnoringWhitespaceSubTitle(), Title: self.c.Tr.UnstagedChanges, NothingToActOn: !node.GetHasUnstagedChanges(), @@ -394,9 +398,9 @@ func (self *FilesController) renderWorkingTreeDiff(node *filetree.FileNode) { } if showStaged { - cmdObj := self.c.Git().WorkingTree.WorktreeFileDiffCmdObj(node, git_commands.DiffModeRendered, true, paths) + cmdObj := self.c.Git().WorkingTree.WorktreeFileDiffCmdObj(node, mode, true, paths) refreshOpts.Secondary = &types.ViewUpdateOpts{ - Task: types.NewRunDiffRendererTask(cmdObj.GetCmd()), + Task: types.NewMainViewDiffTask(cmdObj.GetCmd(), mode), SubTitle: self.c.Helpers().Diff.IgnoringWhitespaceSubTitle(), Title: self.c.Tr.StagedChanges, NothingToActOn: !node.GetHasStagedChanges(), diff --git a/pkg/gui/controllers/helpers/diff_helper.go b/pkg/gui/controllers/helpers/diff_helper.go index 3a8306fc2..fed353d82 100644 --- a/pkg/gui/controllers/helpers/diff_helper.go +++ b/pkg/gui/controllers/helpers/diff_helper.go @@ -55,6 +55,8 @@ func (self *DiffHelper) DiffArgs() []string { // either there's no range, or it can't be diffed for some reason), then we want // to fall back to rendering the diff for the single commit. func (self *DiffHelper) GetUpdateTaskForRenderingCommitsDiff(commit *models.Commit, refRange *types.RefRange) types.UpdateTask { + mode := self.diffLineHelper.MainViewDiffMode() + if refRange != nil { from, to := refRange.From, refRange.To args := []string{from.ParentRefName(), to.RefName(), "--stat", "-p"} @@ -74,13 +76,13 @@ func (self *DiffHelper) GetUpdateTaskForRenderingCommitsDiff(commit *models.Comm args = append(args, filterPath) } } - cmdObj := self.c.Git().Diff.DiffCmdObj(args, git_commands.DiffModeRendered) + cmdObj := self.c.Git().Diff.DiffCmdObj(args, mode) prefix := style.FgYellow.Sprintf("%s %s-%s\n\n", self.c.Tr.ShowingDiffForRange, from.ShortRefName(), to.ShortRefName()) - return types.NewRunDiffRendererTaskWithPrefix(cmdObj.GetCmd(), prefix) + return types.NewMainViewDiffTaskWithPrefix(cmdObj.GetCmd(), prefix, mode) } - cmdObj := self.c.Git().Commit.ShowCmdObj(commit.Hash(), self.FilterPathsForCommit(commit), git_commands.DiffModeRendered) - return types.NewRunDiffRendererTask(cmdObj.GetCmd()) + cmdObj := self.c.Git().Commit.ShowCmdObj(commit.Hash(), self.FilterPathsForCommit(commit), mode) + return types.NewMainViewDiffTask(cmdObj.GetCmd(), mode) } // PlainDiffBetweenRefs returns the diff of the given files between two refs as git diff --git a/pkg/gui/controllers/helpers/diff_line_helper.go b/pkg/gui/controllers/helpers/diff_line_helper.go index 95f95cc59..b26262bba 100644 --- a/pkg/gui/controllers/helpers/diff_line_helper.go +++ b/pkg/gui/controllers/helpers/diff_line_helper.go @@ -9,6 +9,11 @@ import ( type DiffLineHelper struct { c *HelperCommon + + // What the probe said about the diff renderer that rendererSignature names, or nil + // before it has been asked about any (see diffRendererEmitsMetadata). + rendererEmitsMetadata *bool + rendererSignature string } func NewDiffLineHelper(c *HelperCommon) *DiffLineHelper { diff --git a/pkg/gui/controllers/helpers/diff_line_raw_fallback.go b/pkg/gui/controllers/helpers/diff_line_raw_fallback.go new file mode 100644 index 000000000..6f967cd64 --- /dev/null +++ b/pkg/gui/controllers/helpers/diff_line_raw_fallback.go @@ -0,0 +1,112 @@ +package helpers + +import ( + "fmt" + "strings" + + "github.com/jesseduffield/lazygit/pkg/commands/git_commands" + "github.com/jesseduffield/lazygit/pkg/config" + "github.com/jesseduffield/lazygit/pkg/gocui" + "github.com/jesseduffield/lazygit/pkg/gui/types" + "github.com/jesseduffield/lazygit/pkg/tasks" +) + +// Falling back to git's own diff when the configured one can't be acted on. +// +// A diff renderer is free to lay a diff out however it likes, and once it has, we can +// only tell which line of which file a row shows if the renderer says so. A renderer +// that doesn't produces a diff that can be read but not staged, edited or copied from, +// so when the user focuses the main view to act on it, we show git's own diff instead. +// Browsing keeps the renderer's version; only acting on it needs one we can follow. + +// MainViewDiffMode says how a side panel should produce the diff it renders into the +// main view: as the user configured it, or as git's own — while the main view holds +// focus and what the renderer would produce couldn't be acted on. +// +// Every panel that renders a diff into the main view asks, so that a re-render while +// focused — after staging a hunk, say — stays with git's own diff rather than flipping +// back to the renderer's. +func (self *DiffLineHelper) MainViewDiffMode() git_commands.DiffMode { + if self.mainViewIsFocused() && self.diffNeedsMetadata() && !self.diffRendererEmitsMetadata() { + return git_commands.DiffModeRaw + } + return git_commands.DiffModeRendered +} + +// RenderFocusedMainViewAgain has the panel beneath the focused main view render its +// diff again — which, the main view now holding focus, is git's own diff rather than +// the renderer's — and calls place once that is on screen. +// +// The whole diff is read before it is shown, rather than the first screenful: place +// looks at what is there to decide where to put the selection, and a change line +// further down would otherwise be missed. +// +// It is the same diff of the same files, so the view keeps the scroll position it has +// rather than starting from the top: git lays the changes out its own way and the line +// the user was on is somewhere else now, but the offset still puts them among the same +// part of the file — and the selection is then established from what that leaves on +// screen. +func (self *DiffLineHelper) RenderFocusedMainViewAgain(view *gocui.View, sidePanel types.Context, place func()) { + manager := self.c.GetOrCreateViewBufferManagerForView(view) + if manager == nil { + return + } + + manager.SetKeepScrollPositionForNextTask() + manager.SetRestoreForNextTask(&tasks.RenderRestore{ + FirstPaintReady: func() bool { return false }, + Apply: func(swapIn func()) { + swapIn() + place() + }, + }) + + sidePanel.HandleRenderToMain() +} + +func (self *DiffLineHelper) mainViewIsFocused() bool { + current := self.c.Context().CurrentStatic().GetKey() + return current == self.c.Contexts().Normal.GetKey() || + current == self.c.Contexts().NormalSecondary.GetKey() +} + +// diffNeedsMetadata reports whether the diff we would show is one whose rows can only +// be placed in the file by the records the renderer states. Any custom renderer may +// restructure the diff; so may git itself, once the renderer's arguments ask for a word +// diff, whose markup is inline. Plain git output describes itself, and needs no records. +func (self *DiffLineHelper) diffNeedsMetadata() bool { + manager := self.c.State().GetDiffRendererConfigManager() + if manager.GetDiffRendererType() != config.DiffRendererType_RawGit { + return true + } + return len(manager.GetRawGitArgs()) > 0 +} + +// diffRendererEmitsMetadata is the probed verdict about the current diff renderer, asked +// once and remembered until the renderer changes — the user cycling to another one, or a +// changed config being reloaded. +func (self *DiffLineHelper) diffRendererEmitsMetadata() bool { + signature := self.diffRendererSignature() + if self.rendererEmitsMetadata == nil || signature != self.rendererSignature { + verdict := self.c.Git().Diff.ProbeDiffRendererEmitsMetadata() + self.rendererEmitsMetadata = &verdict + self.rendererSignature = signature + } + return *self.rendererEmitsMetadata +} + +// diffRendererSignature identifies the current diff renderer, so that the remembered +// verdict is dropped when it stops describing the renderer we have. The values a command +// is resolved with are no part of its identity, so fixed ones are used. +func (self *DiffLineHelper) diffRendererSignature() string { + manager := self.c.State().GetDiffRendererConfigManager() + index, _ := manager.CurrentDiffRendererIndex() + values := config.DiffRendererValues{} + externalDiff, _ := manager.GetExternalDiffCommand(values) + stdinFilter, _ := manager.GetStdinFilterCommand(values) + return fmt.Sprintf("%d\x00%s\x00%s\x00%s", + index, + externalDiff, + stdinFilter, + strings.Join(manager.GetRawGitArgs(), "\x00")) +} diff --git a/pkg/gui/controllers/reflog_commits_controller.go b/pkg/gui/controllers/reflog_commits_controller.go index bd000214f..10b641d93 100644 --- a/pkg/gui/controllers/reflog_commits_controller.go +++ b/pkg/gui/controllers/reflog_commits_controller.go @@ -1,7 +1,6 @@ package controllers import ( - "github.com/jesseduffield/lazygit/pkg/commands/git_commands" "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/types" @@ -60,9 +59,10 @@ func (self *ReflogCommitsController) GetOnRenderToMain() func() { if commit == nil { task = types.NewRenderStringTask("No reflog history") } else { - cmdObj := self.c.Git().Commit.ShowCmdObj(commit.Hash(), self.c.Helpers().Diff.FilterPathsForCommit(commit), git_commands.DiffModeRendered) + mode := self.c.Helpers().DiffLine.MainViewDiffMode() + cmdObj := self.c.Git().Commit.ShowCmdObj(commit.Hash(), self.c.Helpers().Diff.FilterPathsForCommit(commit), mode) - task = types.NewRunDiffRendererTask(cmdObj.GetCmd()) + task = types.NewMainViewDiffTask(cmdObj.GetCmd(), mode) } self.c.RenderToMainViews(types.RefreshMainOpts{ diff --git a/pkg/gui/controllers/stash_controller.go b/pkg/gui/controllers/stash_controller.go index 762090ae6..7c0b61c66 100644 --- a/pkg/gui/controllers/stash_controller.go +++ b/pkg/gui/controllers/stash_controller.go @@ -3,8 +3,6 @@ package controllers import ( "fmt" - "github.com/jesseduffield/lazygit/pkg/commands/git_commands" - "github.com/jesseduffield/lazygit/pkg/commands/models" "github.com/jesseduffield/lazygit/pkg/gocui" "github.com/jesseduffield/lazygit/pkg/gui/context" @@ -94,10 +92,12 @@ func (self *StashController) GetOnRenderToMain() func() { if stashEntry == nil { task = types.NewRenderStringTask(self.c.Tr.NoStashEntries) } else { + mode := self.c.Helpers().DiffLine.MainViewDiffMode() prefix := style.FgYellow.Sprintf("%s\n\n", stashEntry.Description()) - task = types.NewRunDiffRendererTaskWithPrefix( - self.c.Git().Stash.ShowStashEntryCmdObj(stashEntry.Index, git_commands.DiffModeRendered).GetCmd(), + task = types.NewMainViewDiffTaskWithPrefix( + self.c.Git().Stash.ShowStashEntryCmdObj(stashEntry.Index, mode).GetCmd(), prefix, + mode, ) } diff --git a/pkg/gui/controllers/switch_to_focused_main_view_controller.go b/pkg/gui/controllers/switch_to_focused_main_view_controller.go index 189d3c6ac..b2e85914c 100644 --- a/pkg/gui/controllers/switch_to_focused_main_view_controller.go +++ b/pkg/gui/controllers/switch_to_focused_main_view_controller.go @@ -1,6 +1,7 @@ package controllers import ( + "github.com/jesseduffield/lazygit/pkg/commands/git_commands" "github.com/jesseduffield/lazygit/pkg/gocui" "github.com/jesseduffield/lazygit/pkg/gui/context" "github.com/jesseduffield/lazygit/pkg/gui/types" @@ -83,9 +84,22 @@ func (self *SwitchToFocusedMainViewController) focusMainView(mainViewContext *co mainViewContext.ClearSearchString() self.c.Context().Push(mainViewContext, types.OnFocusOpts{}) - if _, ok := self.context.(types.DiffMainViewContext); ok { - self.c.Helpers().DiffLine.EstablishSelection(mainViewContext, clickedLineIdx) + if _, ok := self.context.(types.DiffMainViewContext); !ok { + return nil } + // The diff on screen was produced for reading, and the renderer that produced it may + // have laid it out in a way that says nothing about which line of which file each row + // is. Now that the user wants to act on it, it is re-rendered as git's own diff — the + // panel below decides that for itself, from the same question — and the selection + // goes on that instead of on rows we can't place. + if self.c.Helpers().DiffLine.MainViewDiffMode() == git_commands.DiffModeRaw { + self.c.Helpers().DiffLine.RenderFocusedMainViewAgain(mainViewContext.GetView(), self.context, func() { + self.c.Helpers().DiffLine.EstablishSelection(mainViewContext, clickedLineIdx) + }) + return nil + } + + self.c.Helpers().DiffLine.EstablishSelection(mainViewContext, clickedLineIdx) return nil } diff --git a/pkg/gui/types/rendering.go b/pkg/gui/types/rendering.go index f88a207b6..6f791d1bf 100644 --- a/pkg/gui/types/rendering.go +++ b/pkg/gui/types/rendering.go @@ -2,6 +2,8 @@ package types import ( "os/exec" + + "github.com/jesseduffield/lazygit/pkg/commands/git_commands" ) type MainContextPair struct { @@ -116,3 +118,18 @@ func NewRunDiffRendererTask(cmd *exec.Cmd) *RunDiffRendererTask { func NewRunDiffRendererTaskWithPrefix(cmd *exec.Cmd, prefix string) *RunDiffRendererTask { return &RunDiffRendererTask{Cmd: cmd, Prefix: prefix} } + +// NewMainViewDiffTask returns the task for rendering a diff into a main view. A diff +// normally goes through the diff renderer, however the render arranges to feed it. A +// diff we are producing with git itself, because the renderer's version of it couldn't +// be acted on, has to keep the renderer out, so it runs as a plain command instead. +func NewMainViewDiffTask(cmd *exec.Cmd, mode git_commands.DiffMode) UpdateTask { + return NewMainViewDiffTaskWithPrefix(cmd, "", mode) +} + +func NewMainViewDiffTaskWithPrefix(cmd *exec.Cmd, prefix string, mode git_commands.DiffMode) UpdateTask { + if mode == git_commands.DiffModeRaw { + return NewRunCommandTaskWithPrefix(cmd, prefix) + } + return NewRunDiffRendererTaskWithPrefix(cmd, prefix) +} diff --git a/pkg/integration/tests/main_view/copy_selected_diff_lines.go b/pkg/integration/tests/main_view/copy_selected_diff_lines.go index 812f4e8fe..26ac538c7 100644 --- a/pkg/integration/tests/main_view/copy_selected_diff_lines.go +++ b/pkg/integration/tests/main_view/copy_selected_diff_lines.go @@ -23,11 +23,13 @@ var CopySelectedDiffLines = NewIntegrationTest(NewIntegrationTestArgs{ // Emulate the clipboard by writing to a file. cfg.GetUserConfig().OS.CopyToClipboardCmd = "printf '%s' {{text}} > clipboard" // A renderer that decorates every line of a diff's body, so that what is on - // screen is not what the diff says. It reads the +/- column, so it wants its - // input uncoloured. + // screen is not what the diff says. It announces the metadata protocol, so that + // its output is taken at its word rather than replaced by git's own; and it + // reads the +/- column, so it wants its input uncoloured. cfg.GetUserConfig().Git.DiffRenderers = []config.DiffRendererConfig{ { - Command: `awk '/^@@/ { body = 1 } body && /^[-+ ]/ { print $0 " <<<"; next } { print }'`, + Command: `printf '\033]1717;1\007'; ` + + `awk '/^@@/ { body = 1 } body && /^[-+ ]/ { print $0 " <<<"; next } { print }'`, ColorArg: "never", }, } diff --git a/pkg/integration/tests/main_view/keep_position_when_switching_diff_renderers.go b/pkg/integration/tests/main_view/keep_position_when_switching_diff_renderers.go index 7241ac9bf..b99917a52 100644 --- a/pkg/integration/tests/main_view/keep_position_when_switching_diff_renderers.go +++ b/pkg/integration/tests/main_view/keep_position_when_switching_diff_renderers.go @@ -16,11 +16,14 @@ var KeepPositionWhenSwitchingDiffRenderers = NewIntegrationTest(NewIntegrationTe Height: 30, SetupConfig: func(cfg *config.AppConfig) { cfg.GetUserConfig().Gui.UseHunkModeInStagingView = false + // Both announce the metadata protocol, so that their output is taken at its + // word and shown as it is; a renderer that says nothing about what it renders + // is replaced by git's own diff as soon as the main view is focused. cfg.GetUserConfig().Git.DiffRenderers = []config.DiffRendererConfig{ - {Name: "plain", Command: "cat"}, + {Name: "plain", Command: `printf '\033]1717;1\007'; cat`}, // The same diff, three lines further down the view. (Lines before the // diff's own header aren't part of it, so it still reads the same.) - {Name: "banner", Command: `printf 'rendered for you\n\n\n'; cat`}, + {Name: "banner", Command: `printf '\033]1717;1\007rendered for you\n\n\n'; cat`}, } }, SetupRepo: func(shell *Shell) { diff --git a/pkg/integration/tests/main_view/keep_selection_visible_when_diff_shrinks.go b/pkg/integration/tests/main_view/keep_selection_visible_when_diff_shrinks.go index 0e8690a0c..657e62e21 100644 --- a/pkg/integration/tests/main_view/keep_selection_visible_when_diff_shrinks.go +++ b/pkg/integration/tests/main_view/keep_selection_visible_when_diff_shrinks.go @@ -12,14 +12,15 @@ var KeepSelectionVisibleWhenDiffShrinks = NewIntegrationTest(NewIntegrationTestA SetupConfig: func(cfg *config.AppConfig) { cfg.GetUserConfig().Gui.UseHunkModeInStagingView = false cfg.GetUserConfig().Git.DiffRenderers = []config.DiffRendererConfig{ - {Command: "cat"}, + {Name: "plain", Command: `printf '\033]1717;1\007'; cat`}, // The same diff in fewer lines, as a renderer that collapses or elides // parts of it would give us: the addition at the end goes, and the hunk // header says so, since a diff that contradicts its own header can't be // read as one. (It has to read all of its input: one that exits early // leaves the render looking like it is still loading, which holds off the // clamping this test is about.) - {Name: "shrinking", Command: `sed -e 's/@@ -1,5 +1,5 @@/@@ -1,5 +1,4 @@/' -e '$d'`}, + {Name: "shrinking", Command: `printf '\033]1717;1\007'; ` + + `sed -e 's/@@ -1,5 +1,5 @@/@@ -1,5 +1,4 @@/' -e '$d'`}, } }, SetupRepo: func(shell *Shell) { diff --git a/pkg/integration/tests/main_view/raw_fallback_under_an_external_diff.go b/pkg/integration/tests/main_view/raw_fallback_under_an_external_diff.go new file mode 100644 index 000000000..4d46f5d74 --- /dev/null +++ b/pkg/integration/tests/main_view/raw_fallback_under_an_external_diff.go @@ -0,0 +1,63 @@ +package main_view + +import ( + "fmt" + "strings" + + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var RawFallbackUnderAnExternalDiff = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Focusing the main view under an external diff that says nothing about its rows brings git's own diff, keeping the scroll position", + ExtraCmdArgs: []string{}, + Skip: false, + Width: 120, + Height: 30, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInStagingView = false + // An external diff whose output has nothing to do with the diff it was given, + // let alone anything to say about which line of which file each row shows. It + // is long enough to be scrolled about in. + cfg.GetUserConfig().Git.DiffRenderers = []config.DiffRendererConfig{ + {Name: "opaque", Type: "extDiff", Command: `sh -c 'seq -f "EXT-%g" 40'`}, + } + }, + SetupRepo: func(shell *Shell) { + lines := make([]string, 40) + for i := range lines { + lines[i] = fmt.Sprintf("line%02d", i+1) + } + shell.CreateFileAndAdd("file1", strings.Join(lines, "\n")+"\n") + shell.Commit("one") + + for _, i := range []int{5, 15, 25, 35} { + lines[i-1] = strings.ToUpper(lines[i-1]) + } + shell.UpdateFile("file1", strings.Join(lines, "\n")+"\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + // Browsing shows what the renderer produced, whatever that is. + t.Views().Main(). + Content(Contains("EXT-1")). + Tap(func() { + t.Views().Files(). + IsFocused(). + Press(keys.Universal.ScrollDownMain). + Press(keys.Universal.ScrollDownMain). + Press(keys.Universal.ScrollDownMain) + }). + OriginY(6). + Tap(func() { + t.Views().Files().Press(keys.Universal.FocusMainView) + }). + IsFocused(). + // Focusing the view to act on it brings git's own diff instead — the + // renderer's rows can't be placed in the file — and leaves the view at the + // offset it was at, rather than at the top. + Content(Contains("+LINE05")). + Content(DoesNotContain("EXT-1")). + OriginY(6). + SelectionIsActive() + }, +}) diff --git a/pkg/integration/tests/main_view/stage_under_conforming_diff_renderer.go b/pkg/integration/tests/main_view/stage_under_conforming_diff_renderer.go new file mode 100644 index 000000000..3b5d24c59 --- /dev/null +++ b/pkg/integration/tests/main_view/stage_under_conforming_diff_renderer.go @@ -0,0 +1,55 @@ +package main_view + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var StageUnderConformingDiffRenderer = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "A diff renderer that announces the metadata protocol is taken at its word, so its diff is what stays on screen when the main view is focused", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInStagingView = false + // A renderer that announces the protocol with a version-only record before + // anything else, then says who it is and passes the diff through. The diff it + // passes through keeps its structure, so the rows can be placed by reading it. + cfg.GetUserConfig().Git.DiffRenderers = []config.DiffRendererConfig{ + {Command: `printf '\033]1717;1\007RENDERED BY ME\n'; cat`}, + } + }, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("file1", "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\nnine\nten\n") + shell.Commit("one") + + shell.UpdateFile("file1", "one\ntwo\nTHREE\nfour\nfive\nsix\nseven\neight\nNINE\nten\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Files().IsFocused() + + // The announcement itself leaves nothing on the screen; the line after it shows + // whose output this is. + t.Views().Main().Content(Contains("RENDERED BY ME")) + + t.Views().Files().Press(keys.Universal.FocusMainView) + + // Focusing left the renderer's output alone, and the selection went on it. + t.Views().Main(). + IsFocused(). + Content(Contains("RENDERED BY ME")). + SelectedLines( + Contains("-three"), + ). + Press(keys.Main.ToggleSelectHunk). + SelectedLines( + Contains("-three"), + Contains("+THREE"), + ). + PressPrimaryAction() + + t.Views().Secondary().ContainsLines( + Contains("-three"), + Contains("+THREE"), + ) + }, +}) diff --git a/pkg/integration/tests/main_view/stage_under_unsupported_diff_renderer.go b/pkg/integration/tests/main_view/stage_under_unsupported_diff_renderer.go new file mode 100644 index 000000000..d229f0ab6 --- /dev/null +++ b/pkg/integration/tests/main_view/stage_under_unsupported_diff_renderer.go @@ -0,0 +1,71 @@ +package main_view + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var StageUnderUnsupportedDiffRenderer = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "A diff renderer that says nothing about what it renders is replaced by git's own diff when the main view is focused, so the diff can still be staged from", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInStagingView = false + // `cat -n` numbers every line, which pushes the +/- column off the start of it: + // the diff can't be read back from the text, and cat says nothing about what it + // is rendering, so there is no way to act on what it produces. + cfg.GetUserConfig().Git.DiffRenderers = []config.DiffRendererConfig{ + {Command: "cat -n"}, + } + }, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("file1", "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\nnine\nten\n") + shell.Commit("one") + + shell.UpdateFile("file1", "one\ntwo\nTHREE\nfour\nfive\nsix\nseven\neight\nNINE\nten\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + // While browsing, the view shows the renderer's output. + t.Views().Files(). + IsFocused(). + Lines( + Contains("file1").IsSelected(), + ) + t.Views().Main().Content(Contains("1 diff --git a/file1 b/file1")) + + // Focusing it to act on it brings git's own diff instead, and the selection goes + // on that. + t.Views().Files().Press(keys.Universal.FocusMainView) + + t.Views().Main(). + IsFocused(). + Content(DoesNotContain("1 diff --git")). + SelectedLines( + Contains("-three"), + ). + Press(keys.Main.ToggleSelectHunk). + SelectedLines( + Contains("-three"), + Contains("+THREE"), + ). + PressPrimaryAction() + + t.Views().Secondary().ContainsLines( + Contains("-three"), + Contains("+THREE"), + ) + // The re-render after staging stays with git's diff, so the next hunk can be + // staged as well. + t.Views().Main(). + IsFocused(). + SelectedLines( + Contains("-nine"), + Contains("+NINE"), + ). + PressPrimaryAction() + + t.Views().Files().Lines( + Contains("M file1"), + ) + }, +}) diff --git a/pkg/integration/tests/test_list.go b/pkg/integration/tests/test_list.go index 79f42c278..6add968cf 100644 --- a/pkg/integration/tests/test_list.go +++ b/pkg/integration/tests/test_list.go @@ -403,6 +403,7 @@ var tests = []*components.IntegrationTest{ main_view.NoSelectionOverACommitLog, main_view.NoSelectionWhenNoChanges, main_view.RangeSelectDiffLines, + main_view.RawFallbackUnderAnExternalDiff, main_view.SearchCollapsesTheSelection, main_view.SearchFollowsTheSelection, main_view.SelectBelowALongCommitMessage, @@ -422,6 +423,8 @@ var tests = []*components.IntegrationTest{ main_view.StageDiffLines, main_view.StageDiffLinesOfAPathWithASpace, main_view.StageRangeSpanningFiles, + main_view.StageUnderConformingDiffRenderer, + main_view.StageUnderUnsupportedDiffRenderer, main_view.UnstageDiffLines, misc.ConfirmOnQuit, misc.CopyConfirmationMessageToClipboard, From b967d0261632d1681af41dad4449b540dc565bda Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Thu, 10 Sep 2026 10:52:09 +0200 Subject: [PATCH 15/21] Show a selection only over the diff the panel offers Some merge conflicts can only be resolved by picking a side. The files panel explains those rather than diffing them, and where one side deleted the file and the other modified it, git's diff of that modification is shown below the explanation. The focused main view took those change lines for a diff of its own. It drew a selection over them and offered to stage hunks of a file whose conflict staging can't resolve. So have a render say whether it holds the diff the panel offers in the main view, and put a selection only on one that does. Every diff render already goes through NewMainViewDiffTask, so it says so for itself; the custom patch preview, assembled as text rather than run as a command, says so through NewMainViewDiffStringTask. Establishing a selection asks the pane the same question rather than looking for change lines itself. The selection has been wrong over this content since "Show a selection in the focused main view" introduced it, and the fix belongs there. It lands here instead because a render had no way to say what it holds until "Show git's own diff when the renderer's can't be acted on" gave every diff render one constructor to go through. Co-Authored-By: Claude Opus 5 (1M context) --- pkg/gui/context/main_context.go | 16 ++++++ pkg/gui/controllers/helpers/diff_helper.go | 2 +- .../helpers/diff_line_selection.go | 8 +-- .../controllers/local_commits_controller.go | 2 +- pkg/gui/main_panels.go | 23 ++++++-- pkg/gui/types/rendering.go | 46 +++++++++++++++- .../no_selection_over_a_conflict_hint.go | 52 +++++++++++++++++++ pkg/integration/tests/test_list.go | 1 + 8 files changed, 138 insertions(+), 12 deletions(-) create mode 100644 pkg/integration/tests/main_view/no_selection_over_a_conflict_hint.go diff --git a/pkg/gui/context/main_context.go b/pkg/gui/context/main_context.go index 92ce65d37..f726b4ea6 100644 --- a/pkg/gui/context/main_context.go +++ b/pkg/gui/context/main_context.go @@ -19,6 +19,11 @@ type MainContext struct { // was worked out from. What there is to select is a property of the content, so an // answer about the content of another render says nothing about this one. selectableContentRenderKey string + // contentIsDiff says the render this pane was last given is the diff the panel + // beneath offers here, rather than a message or an explanation (see + // types.ContentIsDiff). It is known as the render is asked for, well before there + // is any content to look at. + contentIsDiff bool } var ( @@ -65,6 +70,17 @@ func (self *MainContext) SetSelectableContentRenderKey(key string) { self.selectableContentRenderKey = key } +// ContentIsDiff reports whether this pane is showing the panel's diff (see +// contentIsDiff). +func (self *MainContext) ContentIsDiff() bool { + return self.contentIsDiff +} + +// SetContentIsDiff records what kind of render the pane is being given. +func (self *MainContext) SetContentIsDiff(value bool) { + self.contentIsDiff = value +} + func NewMainContext( view *gocui.View, windowName string, diff --git a/pkg/gui/controllers/helpers/diff_helper.go b/pkg/gui/controllers/helpers/diff_helper.go index fed353d82..0c829639c 100644 --- a/pkg/gui/controllers/helpers/diff_helper.go +++ b/pkg/gui/controllers/helpers/diff_helper.go @@ -141,7 +141,7 @@ func (self *DiffHelper) RenderDiff() { self.c.Tr.ShowingGitDiff, "git diff "+strings.Join(args, " "), ) - task := types.NewRunDiffRendererTaskWithPrefix(cmdObj.GetCmd(), prefix) + task := types.NewMainViewDiffTaskWithPrefix(cmdObj.GetCmd(), prefix, git_commands.DiffModeRendered) self.c.RenderToMainViews(types.RefreshMainOpts{ Pair: self.c.MainViewPairs().Normal, diff --git a/pkg/gui/controllers/helpers/diff_line_selection.go b/pkg/gui/controllers/helpers/diff_line_selection.go index 1b42cc181..a8b465140 100644 --- a/pkg/gui/controllers/helpers/diff_line_selection.go +++ b/pkg/gui/controllers/helpers/diff_line_selection.go @@ -30,10 +30,10 @@ func (self *DiffLineHelper) EstablishSelection(mainContext *context.MainContext, mainContext.ResetDiffSelectMode() view := mainContext.GetView() - // The panel beneath renders a diff, but that diff may hold nothing to act on: a - // binary file, or an empty commit. Rendering it worked that out, so the pane is - // already showing no selection and there is nowhere to put one. - if !self.ViewHasChangeLines(view) { + // The pane may hold nothing to act on: a diff of a binary file or an empty commit, + // or content that is no diff of the panel's at all. Rendering it worked that out, + // so the pane is already showing no selection and there is nowhere to put one. + if !mainContext.HasSelectableContent() { return } diff --git a/pkg/gui/controllers/local_commits_controller.go b/pkg/gui/controllers/local_commits_controller.go index 1e1a01427..72c99d2ad 100644 --- a/pkg/gui/controllers/local_commits_controller.go +++ b/pkg/gui/controllers/local_commits_controller.go @@ -727,7 +727,7 @@ func secondaryPatchPanelUpdateOpts(c *ControllerCommon) *types.ViewUpdateOpts { patch := c.Git().Patch.PatchBuilder.RenderAggregatedPatch(false) return &types.ViewUpdateOpts{ - Task: types.NewRenderStringWithoutScrollTask(patch), + Task: types.NewMainViewDiffStringTask(patch), Title: c.Tr.CustomPatch, } } diff --git a/pkg/gui/main_panels.go b/pkg/gui/main_panels.go index ba8e7c200..5db9d1925 100644 --- a/pkg/gui/main_panels.go +++ b/pkg/gui/main_panels.go @@ -66,6 +66,10 @@ func (gui *Gui) RefreshMainView(opts *types.ViewUpdateOpts, context types.Contex view.Subtitle = opts.SubTitle + if mainContext := gui.mainContextForView(view); mainContext != nil { + mainContext.SetContentIsDiff(types.ContentIsDiff(opts.Task)) + } + if err := gui.runTaskForView(view, opts.Task); err != nil { gui.c.Log.Error(err) } @@ -290,6 +294,9 @@ func (gui *Gui) clearMainView(mainContext types.Context) { view.Clear() view.SetOrigin(0, 0) mainContext.SetHasSelectableContent(false) + if pane := gui.mainContextForView(view); pane != nil { + pane.SetContentIsDiff(false) + } gui.State.ContextMgr.UpdateSelectionHighlights() if manager := gui.getViewBufferManagerForView(view); manager != nil { manager.ForgetRenderedContent() @@ -298,10 +305,10 @@ func (gui *Gui) clearMainView(mainContext types.Context) { // updateDiffSelectionVisibility works out whether a main pane holds anything for a // selection to sit on, from what it is now showing: only beneath a panel whose main -// view is a diff, and only while that diff holds something to select — never over a -// message like "No changed files", and never over a diff with nothing in it, such as a -// binary file's or an empty commit's. Whether the selection is then drawn, and drawn as -// the active one, follows from the context stack. +// view is a diff, only while the pane is showing that diff rather than a message like +// "No changed files", and only while the diff holds something to select — never over +// one with nothing in it, such as a binary file's or an empty commit's. Whether the +// selection is then drawn, and drawn as the active one, follows from the context stack. // // It is asked wherever the pane's content changes: as a string is rendered, at the // paint that reveals a command's output, with every further batch of that output, and @@ -379,6 +386,14 @@ func (gui *Gui) readOnUntilTheDiffPaneCanTell(view *gocui.View) { func (gui *Gui) diffPaneHasSomethingToSelect( mainContext *context.MainContext, view *gocui.View, contentIsComplete bool, ) (bool, bool) { + if !mainContext.ContentIsDiff() { + // The pane is holding something other than the panel's diff: a message, or the + // hint shown for a merge conflict that has to be resolved by picking a side, + // which explains itself with a diff of what the sides did. Whatever is in there + // is not ours to act on, so this needs no content to answer either. + return false, true + } + if _, showsDiff := gui.State.ContextMgr.CurrentSide().(types.DiffMainViewContext); !showsDiff { // Under a panel that shows no diff there is nothing to select whatever the pane // ends up holding, so this needs no content to answer. Answering it now matters, diff --git a/pkg/gui/types/rendering.go b/pkg/gui/types/rendering.go index 6f791d1bf..ac8932a9b 100644 --- a/pkg/gui/types/rendering.go +++ b/pkg/gui/types/rendering.go @@ -69,6 +69,9 @@ func NewRenderStringTask(str string) *RenderStringTask { type RenderStringWithoutScrollTask struct { Str string + + // contentIsDiff marks a string that is a panel's own diff; see ContentIsDiff. + contentIsDiff bool } func (t *RenderStringWithoutScrollTask) IsUpdateTask() {} @@ -77,6 +80,16 @@ func NewRenderStringWithoutScrollTask(str string) *RenderStringWithoutScrollTask return &RenderStringWithoutScrollTask{Str: str} } +// NewMainViewDiffStringTask returns the task for rendering a diff we hold as text +// rather than as a command to run — the custom patch being built, which we assemble +// ourselves. The view stays where it is, the patch being rendered again on every +// change to it. +func NewMainViewDiffStringTask(str string) UpdateTask { + task := NewRenderStringWithoutScrollTask(str) + task.contentIsDiff = true + return task +} + type RenderStringWithScrollTask struct { Str string OriginX int @@ -92,6 +105,9 @@ func NewRenderStringWithScrollTask(str string, originX int, originY int) *Render type RunCommandTask struct { Cmd *exec.Cmd Prefix string + + // contentIsDiff marks output that is a panel's own diff; see ContentIsDiff. + contentIsDiff bool } func (t *RunCommandTask) IsUpdateTask() {} @@ -107,6 +123,9 @@ func NewRunCommandTaskWithPrefix(cmd *exec.Cmd, prefix string) *RunCommandTask { type RunDiffRendererTask struct { Cmd *exec.Cmd Prefix string + + // contentIsDiff marks output that is a panel's own diff; see ContentIsDiff. + contentIsDiff bool } func (t *RunDiffRendererTask) IsUpdateTask() {} @@ -123,13 +142,36 @@ func NewRunDiffRendererTaskWithPrefix(cmd *exec.Cmd, prefix string) *RunDiffRend // normally goes through the diff renderer, however the render arranges to feed it. A // diff we are producing with git itself, because the renderer's version of it couldn't // be acted on, has to keep the renderer out, so it runs as a plain command instead. +// +// The task it returns is the one that says its output is a diff, so a pane rendering +// it can be pointed at (see ContentIsDiff). func NewMainViewDiffTask(cmd *exec.Cmd, mode git_commands.DiffMode) UpdateTask { return NewMainViewDiffTaskWithPrefix(cmd, "", mode) } func NewMainViewDiffTaskWithPrefix(cmd *exec.Cmd, prefix string, mode git_commands.DiffMode) UpdateTask { if mode == git_commands.DiffModeRaw { - return NewRunCommandTaskWithPrefix(cmd, prefix) + task := NewRunCommandTaskWithPrefix(cmd, prefix) + task.contentIsDiff = true + return task } - return NewRunDiffRendererTaskWithPrefix(cmd, prefix) + task := NewRunDiffRendererTaskWithPrefix(cmd, prefix) + task.contentIsDiff = true + return task +} + +// ContentIsDiff reports whether the given render fills a main pane with the diff a +// panel offers there, as opposed to a message, a commit log, or a diff that is part of +// an explanation. A selection means the lines of the panel's diff, so it is only over +// such a render that there is anything to point at. +func ContentIsDiff(task UpdateTask) bool { + switch task := task.(type) { + case *RenderStringWithoutScrollTask: + return task.contentIsDiff + case *RunCommandTask: + return task.contentIsDiff + case *RunDiffRendererTask: + return task.contentIsDiff + } + return false } diff --git a/pkg/integration/tests/main_view/no_selection_over_a_conflict_hint.go b/pkg/integration/tests/main_view/no_selection_over_a_conflict_hint.go new file mode 100644 index 000000000..45cd19ce2 --- /dev/null +++ b/pkg/integration/tests/main_view/no_selection_over_a_conflict_hint.go @@ -0,0 +1,52 @@ +package main_view + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var NoSelectionOverAConflictHint = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "The hint for a conflict that has to be resolved by picking a side shows no selection, diff and all", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(config *config.AppConfig) { + config.GetUserConfig().Gui.ShowFileTree = false + }, + SetupRepo: func(shell *Shell) { + shell.RunShellCommand(`echo 1 > foo && echo 1 > bar`) + shell.RunShellCommand(`git checkout -b base && git add . && git commit -m base`) + + // theirs: delete foo, modify bar + shell.RunShellCommand(`git checkout -b theirs`) + shell.RunShellCommand(`git rm foo && echo 2 > bar && git add bar && git commit -m theirs`) + + // ours: modify foo, delete bar + shell.RunShellCommand(`git checkout base && git checkout -b ours`) + shell.RunShellCommand(`echo 2 > foo && git add foo && git rm bar && git commit -m ours`) + + shell.RunCommandExpectError([]string{"git", "merge", "theirs"}) + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + // The hint for a file deleted on one side and modified on the other explains + // itself with a diff of what the other side did. That diff is no more ours to + // stage than the words above it, so the pane holds nothing to point at. + t.Views().Files(). + IsFocused(). + NavigateToLine(Contains("DU bar")). + Tap(func() { + t.Views().Main(). + Content(Contains("Conflict: this file was deleted in the current changes")). + Content(Contains("Incoming changes:")). + Content(Contains("+2")) + }). + Press(keys.Universal.FocusMainView) + + t.Views().Main(). + IsFocused(). + SelectionIsHidden(). + PressPrimaryAction(). + Tap(func() { + t.ExpectToast(Contains("There is nothing to select here")) + }) + }, +}) diff --git a/pkg/integration/tests/test_list.go b/pkg/integration/tests/test_list.go index 6add968cf..d8244e0d6 100644 --- a/pkg/integration/tests/test_list.go +++ b/pkg/integration/tests/test_list.go @@ -401,6 +401,7 @@ var tests = []*components.IntegrationTest{ main_view.NavigateByHunkAndFile, main_view.NoSelectionOverABinaryDiff, main_view.NoSelectionOverACommitLog, + main_view.NoSelectionOverAConflictHint, main_view.NoSelectionWhenNoChanges, main_view.RangeSelectDiffLines, main_view.RawFallbackUnderAnExternalDiff, From 308e696fc7a606954f7726f612d01d9d295abd3b Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Sun, 16 Aug 2026 08:15:53 +0200 Subject: [PATCH 16/21] Cover the cases where the next change isn't the obvious one Three cases where landing on the change that took the place of the one acted on is not the same as landing on the next line, or on the same line number: staging an inserted line moves every later line of the file, so the hunk below it is somewhere else afterwards; consecutive deletions all sit at the same place in the new file, so nothing but their order tells them apart; and unstaging half of a modification carries on in the pane the staged side has, which is where the work was already. Co-authored-by: Claude Opus 5 (1M context) --- ...vance_after_staging_shifts_line_numbers.go | 45 +++++++++++++++++++ .../select_next_change_after_unstaging.go | 45 +++++++++++++++++++ .../select_next_deletion_after_staging_one.go | 43 ++++++++++++++++++ pkg/integration/tests/test_list.go | 3 ++ 4 files changed, 136 insertions(+) create mode 100644 pkg/integration/tests/main_view/advance_after_staging_shifts_line_numbers.go create mode 100644 pkg/integration/tests/main_view/select_next_change_after_unstaging.go create mode 100644 pkg/integration/tests/main_view/select_next_deletion_after_staging_one.go diff --git a/pkg/integration/tests/main_view/advance_after_staging_shifts_line_numbers.go b/pkg/integration/tests/main_view/advance_after_staging_shifts_line_numbers.go new file mode 100644 index 000000000..b7ae3db82 --- /dev/null +++ b/pkg/integration/tests/main_view/advance_after_staging_shifts_line_numbers.go @@ -0,0 +1,45 @@ +package main_view + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var AdvanceAfterStagingShiftsLineNumbers = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Staging a hunk that adds a line still leaves the selection on the next hunk, whose line numbers it moved", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInStagingView = true + }, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("file1", "1\n2\n3\n4\n5\n6\n7\n8\n") + shell.Commit("one") + + // Three change blocks: a modification, an added line, and another modification + // below it. Staging the middle one changes how many lines the file has, and so + // where the last one sits. + shell.UpdateFile("file1", "1\nX\n3\n4\nNEW\n5\n6\nY\n8\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Files(). + IsFocused(). + Press(keys.Universal.FocusMainView) + + t.Views().Main(). + IsFocused(). + SelectedLines( + Contains("-2"), + Contains("+X"), + ). + Press(keys.Main.NextHunk). + SelectedLines( + Contains("+NEW"), + ). + PressPrimaryAction(). + SelectedLines( + Contains("-7"), + Contains("+Y"), + ) + }, +}) diff --git a/pkg/integration/tests/main_view/select_next_change_after_unstaging.go b/pkg/integration/tests/main_view/select_next_change_after_unstaging.go new file mode 100644 index 000000000..6851c92d7 --- /dev/null +++ b/pkg/integration/tests/main_view/select_next_change_after_unstaging.go @@ -0,0 +1,45 @@ +package main_view + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var SelectNextChangeAfterUnstaging = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Taking one line of a staged modification back out of the index moves on to the line that replaced it, in the pane the staged side ended up in", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInStagingView = false + }, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("file1", "c0\na1\na2\na3\nc1\nc2\noldB\nc3\n") + shell.Commit("one") + + // Staged: a block of deletions, and a modification below it. + shell.UpdateFileAndAdd("file1", "c0\nc1\nc2\nnewB\nc3\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Files(). + IsFocused(). + Press(keys.Universal.FocusMainView) + + // The file has nothing but staged changes, so the pane holding them is the only + // one shown. + t.Views().Secondary(). + IsFocused(). + SelectedLines( + Contains("-a1"), + ). + NavigateToLine(Contains("-oldB")). + PressPrimaryAction() + + // The unstaged pane has appeared above, and the work carries on where it was: + // on the line that takes the place of the one taken out. + t.Views().Secondary(). + IsFocused(). + SelectedLines( + Contains("+newB"), + ) + }, +}) diff --git a/pkg/integration/tests/main_view/select_next_deletion_after_staging_one.go b/pkg/integration/tests/main_view/select_next_deletion_after_staging_one.go new file mode 100644 index 000000000..6343c7382 --- /dev/null +++ b/pkg/integration/tests/main_view/select_next_deletion_after_staging_one.go @@ -0,0 +1,43 @@ +package main_view + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var SelectNextDeletionAfterStagingOne = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Staging one deletion in the middle of a block of them moves on to the next, not back to the block's first line", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInStagingView = false + }, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("file1", "keep1\nd1\nd2\nd3\nd4\nkeep2\n") + shell.Commit("one") + + // Four deletions in a row. They all sit at the same place in the new file, so + // that position alone cannot tell them apart. + shell.UpdateFile("file1", "keep1\nkeep2\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Files(). + IsFocused(). + Press(keys.Universal.FocusMainView) + + t.Views().Main(). + IsFocused(). + SelectedLines( + Contains("-d1"), + ). + Press(keys.Universal.NextItem). + Press(keys.Universal.NextItem). + SelectedLines( + Contains("-d3"), + ). + PressPrimaryAction(). + SelectedLines( + Contains("-d4"), + ) + }, +}) diff --git a/pkg/integration/tests/test_list.go b/pkg/integration/tests/test_list.go index d8244e0d6..4e3c834ea 100644 --- a/pkg/integration/tests/test_list.go +++ b/pkg/integration/tests/test_list.go @@ -367,6 +367,7 @@ var tests = []*components.IntegrationTest{ interactive_rebase.SwapInRebaseWithConflictAndEdit, interactive_rebase.SwapWithConflict, interactive_rebase.ViewFilesOfTodoEntries, + main_view.AdvanceAfterStagingShiftsLineNumbers, main_view.ClickSelectsDiffLine, main_view.CommitFromMainView, main_view.CopyRowsThatAreNoDiffLine, @@ -416,6 +417,8 @@ var tests = []*components.IntegrationTest{ main_view.SelectInADiffReadInPart, main_view.SelectLineWhenWholeFileIsOneHunk, main_view.SelectNextChangeAfterStaging, + main_view.SelectNextChangeAfterUnstaging, + main_view.SelectNextDeletionAfterStagingOne, main_view.SelectVisibleChangeOnFocusingMainView, main_view.SelectVisibleHunkOnFocusingMainView, main_view.SelectionCommandsOnlyWhereTheyApply, From 32a9eda127b3f88372792a9ed486b08adbc05431 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Sat, 5 Sep 2026 18:26:51 +0200 Subject: [PATCH 17/21] Replay withheld keys on a later pass of the event loop EndBlockingEvents dispatches the keys buffered during a block from inside its own call, so a keybinding handler runs in the middle of whatever the caller was doing. If a caller ends the block partway through updating the screen, that handler acts on state the caller has yet to finish writing. No caller does that today; both of them end their block from a UI-thread callback of their own, with nothing left to do afterwards. The commit after this one adds a caller that can. It ends the block from a render restore, and a render of the two main panes resolves that restore halfway through laying the panes out. Queue the replay through Update instead, so the buffered keys arrive on a later pass of the loop, as they would have if the user had pressed them then. Input stays withheld until that pass runs. Gui events are dispatched in preference to queued work, so a key pressed in between would otherwise be handled ahead of the keys buffered before it. The replay's error now reaches the error handler along with every other handler's, and EndBlockingEvents has nothing left to return. --- pkg/gocui/block_events_test.go | 54 +++++++++++++++++-- pkg/gocui/gui.go | 41 ++++++++++++-- .../controllers/helpers/app_status_helper.go | 28 ++++++---- pkg/gui/controllers/helpers/refresh_helper.go | 3 +- 4 files changed, 104 insertions(+), 22 deletions(-) diff --git a/pkg/gocui/block_events_test.go b/pkg/gocui/block_events_test.go index 277bac89a..e95b834ff 100644 --- a/pkg/gocui/block_events_test.go +++ b/pkg/gocui/block_events_test.go @@ -50,6 +50,22 @@ func setupKeyRecorder(t *testing.T, g *Gui) (GocuiEvent, *[]int) { return GocuiEvent{Type: eventKey, Key: key}, &fired } +// runQueuedWork runs what the gui has queued for the following passes of the +// event loop, which is where EndBlockingEvents leaves the replay of the keys it +// buffered. +func runQueuedWork(t *testing.T, g *Gui) { + t.Helper() + + for { + ev, ok := g.userEvents.dequeue() + if !ok { + return + } + assert.NoError(t, ev.f(g)) + ev.task.Done() + } +} + func TestBlockingEvents_KeysBufferedAndReplayed(t *testing.T) { g := newTestGui(t) keyEvent, fired := setupKeyRecorder(t, g) @@ -64,12 +80,37 @@ func TestBlockingEvents_KeysBufferedAndReplayed(t *testing.T) { assert.NoError(t, g.handleEvent(&keyEvent)) assert.Len(t, *fired, 1, "buffered keys must not dispatch while blocking") - // Unblocking replays the buffered keys. - assert.NoError(t, g.EndBlockingEvents()) + // Unblocking queues the replay rather than dispatching from here. + g.EndBlockingEvents() + assert.Len(t, *fired, 1, "the replay must wait for the event loop") + + runQueuedWork(t, g) assert.Len(t, *fired, 3, "both buffered keys should replay on unblock") assert.Empty(t, g.bufferedKeyEvents) } +func TestBlockingEvents_KeysArrivingBeforeTheReplayGoBehindIt(t *testing.T) { + g := newTestGui(t) + keyEvent, fired := setupKeyRecorder(t, g) + other := GocuiEvent{Type: eventKey, Key: NewKeyRune('y')} + g.SetKeybinding("main", other.Key, func(*Gui, *View) error { + *fired = append(*fired, 0) + return nil + }) + + g.BeginBlockingEvents() + assert.NoError(t, g.handleEvent(&keyEvent)) + g.EndBlockingEvents() + + // A key pressed while the replay is still queued joins the end of the buffer: + // dispatching it now would put it ahead of the keys buffered before it. + assert.NoError(t, g.handleEvent(&other)) + assert.Empty(t, *fired) + + runQueuedWork(t, g) + assert.Equal(t, []int{1, 0}, *fired, "the keys should arrive in the order they were pressed") +} + func TestBlockingEvents_NestsWithCounter(t *testing.T) { g := newTestGui(t) keyEvent, fired := setupKeyRecorder(t, g) @@ -79,11 +120,13 @@ func TestBlockingEvents_NestsWithCounter(t *testing.T) { assert.NoError(t, g.handleEvent(&keyEvent)) // The inner block ending still leaves us blocked: no replay yet. - assert.NoError(t, g.EndBlockingEvents()) + g.EndBlockingEvents() + runQueuedWork(t, g) assert.Empty(t, *fired) // Only the outermost block ending replays. - assert.NoError(t, g.EndBlockingEvents()) + g.EndBlockingEvents() + runQueuedWork(t, g) assert.Len(t, *fired, 1) } @@ -94,5 +137,6 @@ func TestBlockingEvents_MouseClicksDroppedNotBuffered(t *testing.T) { click := GocuiEvent{Type: eventMouse, Key: NewKeyName(MouseLeft)} assert.NoError(t, g.handleEvent(&click)) assert.Empty(t, g.bufferedKeyEvents, "mouse clicks must be dropped, not buffered") - assert.NoError(t, g.EndBlockingEvents()) + g.EndBlockingEvents() + runQueuedWork(t, g) } diff --git a/pkg/gocui/gui.go b/pkg/gocui/gui.go index 5af5a7cca..144fae11f 100644 --- a/pkg/gocui/gui.go +++ b/pkg/gocui/gui.go @@ -236,10 +236,13 @@ type Gui struct { // blockInputCount, when greater than zero, withholds keyboard input from // the handlers: key events are buffered into bufferedKeyEvents and replayed // once the count drops back to zero, while mouse clicks and hover are - // dropped outright. It's a counter so blocking can nest. Both fields are - // only touched on the UI thread. See BeginBlockingEvents. + // dropped outright. It's a counter so blocking can nest. replayPending says + // that the replay is queued but hasn't run yet, and input is withheld until + // it has. All three fields are only touched on the UI thread. See + // BeginBlockingEvents. blockInputCount int bufferedKeyEvents []GocuiEvent + replayPending bool } type NewGuiOpts struct { @@ -936,12 +939,33 @@ func (g *Gui) BeginBlockingEvents() { // normal dispatch path, so they act on the now-current context (a key whose // binding no longer exists is simply ignored, just as if it had been pressed // now). Must be called on the UI thread. -func (g *Gui) EndBlockingEvents() error { +// +// The replay is queued rather than run here, so that the buffered keys arrive on +// a later pass of the event loop, as they would have if the user had pressed them +// then. Running them here dispatches them from the middle of whatever the caller +// was doing. If a caller ends the block partway through updating the screen, a +// handler then acts on state the caller has yet to finish writing. +func (g *Gui) EndBlockingEvents() { g.blockInputCount-- if g.blockInputCount > 0 { - return nil + return } + // Input stays withheld until the replay has run. Gui events are dispatched in + // preference to queued work (see processRemainingEvents), so a key pressed + // before the replay gets its turn would otherwise be handled ahead of the keys + // buffered before it. + g.replayPending = true + g.Update(func(*Gui) error { return g.replayBufferedKeys() }) +} + +// replayBufferedKeys dispatches the keys withheld while input was blocked, and +// lets input through again. One of their handlers may block input afresh, and +// then the keys after it are withheld in their turn, to be replayed when that +// block ends. +func (g *Gui) replayBufferedKeys() error { + g.replayPending = false + buffered := g.bufferedKeyEvents g.bufferedKeyEvents = nil for i := range buffered { @@ -1212,7 +1236,7 @@ func (g *Gui) processRemainingEvents() (bool, error) { // handleEvent handles an event, based on its type (key-press, error, // etc.) func (g *Gui) handleEvent(ev *GocuiEvent) error { - if g.blockInputCount > 0 && eventWithheldWhileBlocking(ev) { + if g.withholdingInput() && eventWithheldWhileBlocking(ev) { if ev.Type == eventKey { // Buffer keys so they replay against fresh state on unblock. g.bufferedKeyEvents = append(g.bufferedKeyEvents, *ev) @@ -1241,6 +1265,13 @@ func (g *Gui) handleEvent(ev *GocuiEvent) error { } } +// withholdingInput reports whether events are being kept from the handlers. They +// are while a block is in force, and on until the keys it buffered have been +// replayed. +func (g *Gui) withholdingInput() bool { + return g.blockInputCount > 0 || g.replayPending +} + // eventWithheldWhileBlocking reports whether an event must not reach the // handlers while input is blocked (see BeginBlockingEvents). Key events are // withheld (buffered for replay); mouse clicks and hover are withheld (dropped). diff --git a/pkg/gui/controllers/helpers/app_status_helper.go b/pkg/gui/controllers/helpers/app_status_helper.go index 44de70546..20e5824e9 100644 --- a/pkg/gui/controllers/helpers/app_status_helper.go +++ b/pkg/gui/controllers/helpers/app_status_helper.go @@ -99,21 +99,27 @@ func (self *AppStatusHelper) WithWaitingStatusBlockingInput(opts types.WaitingSt self.modeHelper.SetSuppressWorkingTreeStateMode(true) } self.c.OnWorker(func(task gocui.Task) error { - // End the block and restore the mode indicator once the operation and its - // refresh have applied their UI updates: OnUIThread queues this after the - // refresh's model bounces and Then (which RefreshFromWorker has already - // enqueued by the time f returns), so the replayed keys act on the - // refreshed state and any resulting working tree state shows correctly. - defer self.c.OnUIThread(func() error { - if opts.HideWorkingTreeState { - self.modeHelper.SetSuppressWorkingTreeStateMode(false) - } - return self.c.GocuiGui().EndBlockingEvents() - }) + defer self.endBlockingInput(opts.HideWorkingTreeState) return self.WithWaitingStatusImpl(opts.Message, f, task) }) } +// endBlockingInput lets input through again once the operation and its refresh +// have applied their UI updates, and restores the mode indicator with it. +// OnUIThread queues this after the refresh's model bounces and Then (which +// RefreshFromWorker has already enqueued by the time the operation returns), so +// the replayed keys act on the refreshed state and any resulting working tree +// state shows correctly. +func (self *AppStatusHelper) endBlockingInput(hideWorkingTreeState bool) { + self.c.OnUIThread(func() error { + if hideWorkingTreeState { + self.modeHelper.SetSuppressWorkingTreeStateMode(false) + } + self.c.GocuiGui().EndBlockingEvents() + return nil + }) +} + func (self *AppStatusHelper) HasStatus() bool { return self.statusMgr().HasStatus() } diff --git a/pkg/gui/controllers/helpers/refresh_helper.go b/pkg/gui/controllers/helpers/refresh_helper.go index 6c96d79c6..92b0b0e84 100644 --- a/pkg/gui/controllers/helpers/refresh_helper.go +++ b/pkg/gui/controllers/helpers/refresh_helper.go @@ -589,7 +589,8 @@ func (self *RefreshHelper) performRefresh(options types.RefreshOptions, calledFr // this runs — and the keys buffered during the refresh replay — // the refreshed state is in place. self.c.OnUIThread(func() error { - return self.c.GocuiGui().EndBlockingEvents() + self.c.GocuiGui().EndBlockingEvents() + return nil }) } From 603e254ec4532e459ee00352105e89150100bcd9 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Sun, 16 Aug 2026 08:28:19 +0200 Subject: [PATCH 18/21] Hold input back until the selection has moved on MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two space presses in quick succession only staged one hunk. Input is withheld until the refresh has landed, which is enough where the diff is rebuilt on the spot, but the main view re-renders asynchronously: the selection only moves to the next change once that render is on screen, so the second press acted on lines that were no longer in the diff, and staged nothing. So the wait is now for the selection to be where the work carries on from, rather than for the model. A restore therefore has to say when it is done — which it can be either way, since a view given a message rather than a re-render now gives up the restore it was holding instead of leaving it to claim some later render. Co-authored-by: Claude Opus 5 (1M context) --- .../controllers/helpers/diff_line_restore.go | 15 +++++- pkg/gui/controllers/main_view_controller.go | 9 +++- .../controllers/working_tree_diff_actions.go | 8 ++- pkg/gui/main_panels.go | 5 ++ pkg/gui/tasks_adapter.go | 9 ++++ .../stage_hunks_with_rapid_keypresses.go | 54 +++++++++++++++++++ pkg/integration/tests/test_list.go | 1 + pkg/tasks/tasks.go | 35 ++++++++++++ 8 files changed, 132 insertions(+), 4 deletions(-) create mode 100644 pkg/integration/tests/main_view/stage_hunks_with_rapid_keypresses.go diff --git a/pkg/gui/controllers/helpers/diff_line_restore.go b/pkg/gui/controllers/helpers/diff_line_restore.go index 31cdcd967..38a070717 100644 --- a/pkg/gui/controllers/helpers/diff_line_restore.go +++ b/pkg/gui/controllers/helpers/diff_line_restore.go @@ -261,6 +261,7 @@ func (self *DiffLineHelper) restoreDiffLinePositionOnRerender( return bufferLine, true }, func(viewLine int) { place(found, viewLine) }, + nil, ) } @@ -288,7 +289,13 @@ func (self *DiffLineHelper) ChangeLineOrdinal(view *gocui.View, bufferLine int) // user, this is where what they were doing carries on. When the new diff has fewer // changes than that, because the ones acted on were its last, it lands on the last // change left. -func (self *DiffLineHelper) RevealChangeLineAtOrdinal(view *gocui.View, ordinal int, place func(viewLine int)) { +// +// done is called once the selection is where it belongs, or once it turns out that no +// render is coming to put it there, for a caller that must not let the user act again +// in between. +func (self *DiffLineHelper) RevealChangeLineAtOrdinal( + view *gocui.View, ordinal int, place func(viewLine int), done func(), +) { // How many change lines the incremental search has passed, so that it can carry on // counting where it left off. seen := 0 @@ -320,6 +327,7 @@ func (self *DiffLineHelper) RevealChangeLineAtOrdinal(view *gocui.View, ordinal return last, last != -1 }, place, + done, ) } @@ -339,12 +347,16 @@ func (self *DiffLineHelper) installDiffLineRestore( findEarly func(rows []gocui.DiffLineContent, offset int) (int, bool), findComplete func(contents []gocui.DiffLineContent) (int, bool), place func(viewLine int), + done func(), ) { // Get-or-create, because the pane may not have rendered anything yet: a file whose // diff has only just become split has a second pane whose first render is the one // this restore is for. manager := self.c.GetOrCreateViewBufferManagerForView(view) if manager == nil { + if done != nil { + done() + } return } @@ -390,6 +402,7 @@ func (self *DiffLineHelper) installDiffLineRestore( place(viewLine) } }, + Done: done, }) } diff --git a/pkg/gui/controllers/main_view_controller.go b/pkg/gui/controllers/main_view_controller.go index 62953a844..949fae006 100644 --- a/pkg/gui/controllers/main_view_controller.go +++ b/pkg/gui/controllers/main_view_controller.go @@ -347,8 +347,13 @@ func (self *MainViewController) primaryAction() error { // target pane inherits that select mode, this being the same piece of work continuing // in another pane — and shows no selection until the restore places one, so that what // it was left showing the last time it was used doesn't appear for a frame. +// +// done is called once the selection is where it belongs, or once it turns out that no +// render is coming to put it there, for a caller that must not let the user act again +// in between. func revealSelectionAfterAction( - c *ControllerCommon, source types.DiffPaneContext, target types.DiffPaneContext, firstBufferLine int, + c *ControllerCommon, source types.DiffPaneContext, target types.DiffPaneContext, + firstBufferLine int, done func(), ) { ordinal := c.Helpers().DiffLine.ChangeLineOrdinal(source.GetView(), firstBufferLine) @@ -373,7 +378,7 @@ func revealSelectionAfterAction( } targetView.CancelRangeSelect() c.Helpers().DiffLine.ShowSelectionAtLine(targetView, viewLine, true) - }) + }, done) } // discardSelection takes the selected diff lines back out of what they are part of, diff --git a/pkg/gui/controllers/working_tree_diff_actions.go b/pkg/gui/controllers/working_tree_diff_actions.go index 8070e0e7e..75b5f97fc 100644 --- a/pkg/gui/controllers/working_tree_diff_actions.go +++ b/pkg/gui/controllers/working_tree_diff_actions.go @@ -282,7 +282,13 @@ func (self *WorkingTreeDiffActions) revealSelectionInPaneItLandsIn( target = self.otherPane(pane) } - revealSelectionAfterAction(self.c, pane, target, firstBufferLine) + // Hold input back until the selection is on the change the work carries on from. The + // refresh holds it until the model is up to date, but the diff is re-rendered after + // that, and until it has been the selection is still on lines that aren't there any + // more — so a key pressed meanwhile would act on nothing. + self.c.GocuiGui().BeginBlockingEvents() + revealSelectionAfterAction(self.c, pane, target, firstBufferLine, + self.c.GocuiGui().EndBlockingEvents) } // otherPane returns the main pane that isn't the given one. diff --git a/pkg/gui/main_panels.go b/pkg/gui/main_panels.go index 5db9d1925..b6d748f53 100644 --- a/pkg/gui/main_panels.go +++ b/pkg/gui/main_panels.go @@ -289,6 +289,10 @@ func (gui *Gui) clampDiffSelectionToContent(view *gocui.View) { // An emptied pane is showing nothing, so it also goes back to the top and stops // claiming the render it was showing: whatever it is given next is content the user // hasn't seen there, and is shown from the top like any other. +// +// A position waiting to be put back goes too: this pane is getting no render for it +// to ride, and whoever is waiting for the view to be back where it belongs has to +// hear that it never will be. func (gui *Gui) clearMainView(mainContext types.Context) { view := mainContext.GetView() view.Clear() @@ -300,6 +304,7 @@ func (gui *Gui) clearMainView(mainContext types.Context) { gui.State.ContextMgr.UpdateSelectionHighlights() if manager := gui.getViewBufferManagerForView(view); manager != nil { manager.ForgetRenderedContent() + manager.DropRestoreForNextTask() } } diff --git a/pkg/gui/tasks_adapter.go b/pkg/gui/tasks_adapter.go index 54903d1c9..4aea2a3b9 100644 --- a/pkg/gui/tasks_adapter.go +++ b/pkg/gui/tasks_adapter.go @@ -93,6 +93,9 @@ func (gui *Gui) newStringTask(view *gocui.View, str string) error { func (gui *Gui) newStringTaskWithoutScroll(view *gocui.View, str string) error { manager := gui.getManager(view) + // Whatever the view was going to be put back to belonged to a re-render of its + // content; this is a message instead, so there is nothing to put back. + manager.DropRestoreForNextTask() f := func(tasks.TaskOpts) error { return gui.g.OnUIThreadAndWaitBackground(func() { @@ -111,6 +114,9 @@ func (gui *Gui) newStringTaskWithoutScroll(view *gocui.View, str string) error { func (gui *Gui) newStringTaskWithScroll(view *gocui.View, str string, originX int, originY int) error { manager := gui.getManager(view) + // Whatever the view was going to be put back to belonged to a re-render of its + // content; this is a message instead, so there is nothing to put back. + manager.DropRestoreForNextTask() f := func(tasks.TaskOpts) error { return gui.g.OnUIThreadAndWaitBackground(func() { @@ -130,6 +136,9 @@ func (gui *Gui) newStringTaskWithScroll(view *gocui.View, str string, originX in func (gui *Gui) newStringTaskWithKey(view *gocui.View, str string, key string) error { manager := gui.getManager(view) + // Whatever the view was going to be put back to belonged to a re-render of its + // content; this is a message instead, so there is nothing to put back. + manager.DropRestoreForNextTask() f := func(tasks.TaskOpts) error { return gui.g.OnUIThreadAndWaitBackground(func() { diff --git a/pkg/integration/tests/main_view/stage_hunks_with_rapid_keypresses.go b/pkg/integration/tests/main_view/stage_hunks_with_rapid_keypresses.go new file mode 100644 index 000000000..400f84847 --- /dev/null +++ b/pkg/integration/tests/main_view/stage_hunks_with_rapid_keypresses.go @@ -0,0 +1,54 @@ +package main_view + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +// The second space is pressed before the diff the first one changed has re-rendered. +// The selection only moves to the next hunk once that render arrives, so until then it +// still covers lines that are no longer in the diff. The second press has to wait for +// the render rather than act on those lines. +var StageHunksWithRapidKeypresses = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Stage two hunks from the focused main view with two space presses in rapid succession", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInStagingView = true + }, + SetupRepo: func(shell *Shell) { + // Seven context lines between the two change blocks, so that git makes them two + // hunks. + shell.CreateFileAndAdd("file1", "1\n2\na\nb\nc\nd\ne\nf\ng\n3\n4\n") + shell.Commit("one") + + shell.UpdateFile("file1", "1b\n2b\na\nb\nc\nd\ne\nf\ng\n3b\n4b\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Files(). + IsFocused(). + Lines( + Contains("file1").IsSelected(), + ). + Press(keys.Universal.FocusMainView) + + t.Views().Main(). + IsFocused(). + PressRapidly(keys.Universal.Select, keys.Universal.Select) + + // Both presses were acted on, so the whole file is staged. + t.Views().Files().Lines( + Contains("M file1"), + ) + t.Views().Secondary(). + Title(Equals("Staged changes")). + ContainsLines( + Contains("+1b"), + Contains("+2b"), + ). + ContainsLines( + Contains("+3b"), + Contains("+4b"), + ) + }, +}) diff --git a/pkg/integration/tests/test_list.go b/pkg/integration/tests/test_list.go index 4e3c834ea..eceaa02e6 100644 --- a/pkg/integration/tests/test_list.go +++ b/pkg/integration/tests/test_list.go @@ -426,6 +426,7 @@ var tests = []*components.IntegrationTest{ main_view.StageDeletedFile, main_view.StageDiffLines, main_view.StageDiffLinesOfAPathWithASpace, + main_view.StageHunksWithRapidKeypresses, main_view.StageRangeSpanningFiles, main_view.StageUnderConformingDiffRenderer, main_view.StageUnderUnsupportedDiffRenderer, diff --git a/pkg/tasks/tasks.go b/pkg/tasks/tasks.go index dbc83758a..c1656b2de 100644 --- a/pkg/tasks/tasks.go +++ b/pkg/tasks/tasks.go @@ -195,6 +195,24 @@ type RenderRestore struct { // case the view keeps the position the paint gave it: the offset it had, or the // top for content the view hasn't seen. Apply func(swapIn func()) + + // Done is called once the restore has had its render — after Apply, or when it + // is given up because the view is being shown something other than a re-render + // of what it was remembered from. It is how a caller that has to wait for the + // view to be back where it belongs knows that it either is, or never will be. + // Optional, and called on the UI thread, as Apply is. + Done func() +} + +// resolved reports that this restore's render has happened, or that there will not be +// one. Called on the UI thread, from wherever the restore ends: once, whichever way it +// ended. +func (self *RenderRestore) resolved() { + if self.Done != nil { + done := self.Done + self.Done = nil + done() + } } // SetRestoreForNextTask arranges for the next command task to put the view back @@ -254,6 +272,22 @@ func (self *ViewBufferManager) clearRestore(restore *RenderRestore) { } } +// DropRestoreForNextTask gives up a restore that has no render to ride, because the +// view is being given something other than a re-render of the content it was +// remembered from — a message where a diff was. Without this the restore would sit +// there and claim some later render of that view, putting the user somewhere they +// haven't been for a while. +func (self *ViewBufferManager) DropRestoreForNextTask() { + self.taskIDMutex.Lock() + restore := self.restoreForNextTask + self.restoreForNextTask = nil + self.taskIDMutex.Unlock() + + if restore != nil { + restore.resolved() + } +} + func (self *ViewBufferManager) GetTaskKey() string { self.taskIDMutex.Lock() defer self.taskIDMutex.Unlock() @@ -566,6 +600,7 @@ func (self *ViewBufferManager) NewCmdTask(start func() (Cmd, io.Reader), prefix // user was in the new content before it is revealed. restore.Apply(self.swapInRender) self.clearRestore(restore) + restore.resolved() return } self.swapInRender() From 11eeac0481d6509505e5a5821cc3c8e55e42f133 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 1 Sep 2026 19:01:23 +0200 Subject: [PATCH 19/21] Ask a parsed patch which of its lines a selection covers Staging a selection walks the file's diff to find the lines the user pointed at, by where each of them sits in the file. The next commit needs the same answer for a single row, so pull the walk out of the staging path before there are two copies of it. Co-authored-by: Claude Opus 5 (1M context) --- .../controllers/working_tree_diff_actions.go | 65 +++++++++++-------- 1 file changed, 37 insertions(+), 28 deletions(-) diff --git a/pkg/gui/controllers/working_tree_diff_actions.go b/pkg/gui/controllers/working_tree_diff_actions.go index 75b5f97fc..233ecec13 100644 --- a/pkg/gui/controllers/working_tree_diff_actions.go +++ b/pkg/gui/controllers/working_tree_diff_actions.go @@ -198,34 +198,7 @@ func (self *WorkingTreeDiffActions) applyDiffLines( ) (bool, error) { parsedPatch := patch.Parse(self.c.Git().WorkingTree.WorktreeFileDiff(file, git_commands.DiffModePlain, sourceCached)) - type changeLine struct { - lineNumber int - isDeletion bool - } - selected := set.New[changeLine]() - for _, info := range infos { - if info.Type == types.DiffLineDeleted { - selected.Add(changeLine{info.OldLine, true}) - } else { - selected.Add(changeLine{info.NewLine, false}) - } - } - - var patchLineIndices []int - for idx, line := range parsedPatch.Lines() { - var key changeLine - switch { - case line.IsAddition(): - key = changeLine{parsedPatch.LineNumberOfLine(idx), false} - case line.IsDeletion(): - key = changeLine{parsedPatch.OldLineNumberOfLine(idx), true} - default: - continue - } - if selected.Includes(key) { - patchLineIndices = append(patchLineIndices, idx) - } - } + patchLineIndices := changeLineIndices(parsedPatch, infos) changesLeft := len(patchLineIndices) < changeLineCount(parsedPatch) @@ -256,6 +229,42 @@ func (self *WorkingTreeDiffActions) applyDiffLines( return changesLeft, self.c.Git().Patch.ApplyPatch(patchToApply, opts) } +// changeLineIndices says which lines of a parsed patch the given diff rows are, as the +// indices a patch is built in terms of. Each row is looked for by where it sits in the +// file: an addition by its place in the new version, a deletion by its place in the +// old one, which is what tells the two halves of a changed line apart. +func changeLineIndices(parsedPatch *patch.Patch, infos []types.DiffLineInfo) []int { + type changeLine struct { + lineNumber int + isDeletion bool + } + selected := set.New[changeLine]() + for _, info := range infos { + if info.Type == types.DiffLineDeleted { + selected.Add(changeLine{info.OldLine, true}) + } else { + selected.Add(changeLine{info.NewLine, false}) + } + } + + var indices []int + for idx, line := range parsedPatch.Lines() { + var key changeLine + switch { + case line.IsAddition(): + key = changeLine{parsedPatch.LineNumberOfLine(idx), false} + case line.IsDeletion(): + key = changeLine{parsedPatch.OldLineNumberOfLine(idx), true} + default: + continue + } + if selected.Includes(key) { + indices = append(indices, idx) + } + } + return indices +} + // changeLineCount returns how many of a patch's lines are changes rather than context // or header. A selection of the whole diff covers exactly that many. func changeLineCount(p *patch.Patch) int { From 3e3bdb9ff39cbf9fa6d99b8290b60ace86720e99 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 1 Sep 2026 21:43:13 +0200 Subject: [PATCH 20/21] Don't refresh while the editor still has the hunk Editing a hunk points an editor at a patch we wrote to a temp file and waits. Nothing about the repo has changed when the editor returns: the change lands when the caller applies what came back. But the suspend path this went through refreshes as soon as the subprocess exits, so it reads the state from before the patch is applied and then races the caller's own refresh to publish it. Whichever lands last wins, and when it is the stale one the files panel goes on showing the file as it was before the edit until something else refreshes. The caller is the one that knows when there is something new to see, and both callers already refresh once they have applied the patch, so the refresh in the middle only ever had a wrong answer to give. Being a publish-order race, it doesn't reproduce reliably enough for a test; holding a background refresh between its read and its publish shows it every time. Co-authored-by: Claude Opus 5 (1M context) --- pkg/gui/controllers/helpers/files_helper.go | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/pkg/gui/controllers/helpers/files_helper.go b/pkg/gui/controllers/helpers/files_helper.go index 81c9b272e..1f7ed5188 100644 --- a/pkg/gui/controllers/helpers/files_helper.go +++ b/pkg/gui/controllers/helpers/files_helper.go @@ -46,8 +46,16 @@ func (self *FilesHelper) EditFileAtLineAndWait(filename string, lineNumber int) // Always suspend, regardless of the value of the suspend config, // since we want to prevent interacting with the UI until the editor - // returns, even if the editor doesn't use the terminal - return self.callEditor(cmdStr, true) + // returns, even if the editor doesn't use the terminal. + // + // And nothing is refreshed here; that is why this doesn't go through + // callEditor. The editor was handed a patch we wrote for it, so the repo + // hasn't changed when it returns; it changes when the caller applies what + // came back. A refresh in between reads the state from before that, and + // then races the caller's own refresh to publish it. + _, err = self.c.RunSubprocess( + self.c.OS().Cmd.NewShell(cmdStr, self.c.UserConfig().OS.ShellFunctionsFile)) + return err } func (self *FilesHelper) OpenDirInEditor(path string) error { From 11671fd86e9fd91a86efb2976c07b367afc89d3d Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 1 Sep 2026 19:30:33 +0200 Subject: [PATCH 21/21] Edit the selected hunk from the focused main view The staging view can hand the hunk you are on to an editor and apply what comes back, which is how you stage something the diff cannot express: half of a changed line, or a change written differently from either side. The focused main view has to be able to do the same before that view can go. The hunk is git's own, context and all, rather than lazygit's block of adjacent changes: an editable patch is one that still applies, and the context lines are what let git place it. What the editor leaves behind is applied whole rather than matched against the file's diff again, the point being that it says something the diff didn't. Co-authored-by: Claude Opus 5 (1M context) --- docs-master/keybindings/Keybindings_en.md | 2 + docs-master/keybindings/Keybindings_ja.md | 2 + docs-master/keybindings/Keybindings_ko.md | 2 + docs-master/keybindings/Keybindings_nl.md | 2 + docs-master/keybindings/Keybindings_pl.md | 2 + docs-master/keybindings/Keybindings_pt.md | 2 + docs-master/keybindings/Keybindings_ru.md | 2 + docs-master/keybindings/Keybindings_zh-CN.md | 2 + docs-master/keybindings/Keybindings_zh-TW.md | 2 + pkg/gui/controllers/main_view_controller.go | 23 ++++++ .../controllers/working_tree_diff_actions.go | 82 +++++++++++++++++++ .../main_view/edit_hunk_in_focused_diff.go | 59 +++++++++++++ pkg/integration/tests/test_list.go | 1 + 13 files changed, 183 insertions(+) create mode 100644 pkg/integration/tests/main_view/edit_hunk_in_focused_diff.go diff --git a/docs-master/keybindings/Keybindings_en.md b/docs-master/keybindings/Keybindings_en.md index 20bca0c61..bd1322940 100644 --- a/docs-master/keybindings/Keybindings_en.md +++ b/docs-master/keybindings/Keybindings_en.md @@ -228,6 +228,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` e `` | Edit file | Open file in external editor. | | `` `` | Stage | Toggle selection staged / unstaged. | | `` d `` | Discard | When unstaged change is selected, discard the change using `git reset`. When staged change is selected, unstage the change. | +| `` E `` | Edit hunk | Edit selected hunk in external editor. | | `` `` | Copy selected text to clipboard | | | `` , h `` | Go to previous hunk | | | `` , l `` | Go to next hunk | | @@ -347,6 +348,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` e `` | Edit file | Open file in external editor. | | `` `` | Stage | Toggle selection staged / unstaged. | | `` d `` | Discard | When unstaged change is selected, discard the change using `git reset`. When staged change is selected, unstage the change. | +| `` E `` | Edit hunk | Edit selected hunk in external editor. | | `` `` | Copy selected text to clipboard | | | `` , h `` | Go to previous hunk | | | `` , l `` | Go to next hunk | | diff --git a/docs-master/keybindings/Keybindings_ja.md b/docs-master/keybindings/Keybindings_ja.md index 6d2767953..7acb4556d 100644 --- a/docs-master/keybindings/Keybindings_ja.md +++ b/docs-master/keybindings/Keybindings_ja.md @@ -197,6 +197,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` e `` | ファイルを編集 | 外部エディタでファイルを開きます。 | | `` `` | ステージ | 選択された部分のステージ / アンステージを切り替えます。 | | `` d `` | 破棄 | ステージされていない変更が選択されている場合、`git reset`を使用して変更を破棄します。ステージされた変更が選択されている場合、変更をアンステージします。 | +| `` E `` | ハンクを編集 | 選択したハンクを外部エディタで編集します。 | | `` `` | 選択したテキストをクリップボードにコピー | | | `` , h `` | 前のハンクに移動 | | | `` , l `` | 次のハンクに移動 | | @@ -324,6 +325,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` e `` | ファイルを編集 | 外部エディタでファイルを開きます。 | | `` `` | ステージ | 選択された部分のステージ / アンステージを切り替えます。 | | `` d `` | 破棄 | ステージされていない変更が選択されている場合、`git reset`を使用して変更を破棄します。ステージされた変更が選択されている場合、変更をアンステージします。 | +| `` E `` | ハンクを編集 | 選択したハンクを外部エディタで編集します。 | | `` `` | 選択したテキストをクリップボードにコピー | | | `` , h `` | 前のハンクに移動 | | | `` , l `` | 次のハンクに移動 | | diff --git a/docs-master/keybindings/Keybindings_ko.md b/docs-master/keybindings/Keybindings_ko.md index dab679603..f83706741 100644 --- a/docs-master/keybindings/Keybindings_ko.md +++ b/docs-master/keybindings/Keybindings_ko.md @@ -89,6 +89,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` e `` | 파일 편집 | Open file in external editor. | | `` `` | Staged 전환 | 선택한 행을 staged / unstaged | | `` d `` | 변경을 삭제 (git reset) | When unstaged change is selected, discard the change using `git reset`. When staged change is selected, unstage the change. | +| `` E `` | Edit hunk | Edit selected hunk in external editor. | | `` `` | 선택한 텍스트를 클립보드에 복사 | | | `` , h `` | 이전 hunk를 선택 | | | `` , l `` | 다음 hunk를 선택 | | @@ -181,6 +182,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` e `` | 파일 편집 | Open file in external editor. | | `` `` | Staged 전환 | 선택한 행을 staged / unstaged | | `` d `` | 변경을 삭제 (git reset) | When unstaged change is selected, discard the change using `git reset`. When staged change is selected, unstage the change. | +| `` E `` | Edit hunk | Edit selected hunk in external editor. | | `` `` | 선택한 텍스트를 클립보드에 복사 | | | `` , h `` | 이전 hunk를 선택 | | | `` , l `` | 다음 hunk를 선택 | | diff --git a/docs-master/keybindings/Keybindings_nl.md b/docs-master/keybindings/Keybindings_nl.md index f336abffa..2520842b4 100644 --- a/docs-master/keybindings/Keybindings_nl.md +++ b/docs-master/keybindings/Keybindings_nl.md @@ -236,6 +236,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` e `` | Verander bestand | Open bestand in externe editor. | | `` `` | Toggle staged | Toggle lijnen staged / unstaged | | `` d `` | Verwijdert change (git reset) | When unstaged change is selected, discard the change using `git reset`. When staged change is selected, unstage the change. | +| `` E `` | Edit hunk | Edit selected hunk in external editor. | | `` `` | Copy selected text to clipboard | | | `` , h `` | Selecteer de vorige hunk | | | `` , l `` | Selecteer de volgende hunk | | @@ -325,6 +326,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` e `` | Verander bestand | Open bestand in externe editor. | | `` `` | Toggle staged | Toggle lijnen staged / unstaged | | `` d `` | Verwijdert change (git reset) | When unstaged change is selected, discard the change using `git reset`. When staged change is selected, unstage the change. | +| `` E `` | Edit hunk | Edit selected hunk in external editor. | | `` `` | Copy selected text to clipboard | | | `` , h `` | Selecteer de vorige hunk | | | `` , l `` | Selecteer de volgende hunk | | diff --git a/docs-master/keybindings/Keybindings_pl.md b/docs-master/keybindings/Keybindings_pl.md index b9f928561..846194c46 100644 --- a/docs-master/keybindings/Keybindings_pl.md +++ b/docs-master/keybindings/Keybindings_pl.md @@ -104,6 +104,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` e `` | Edytuj plik | Otwórz plik w zewnętrznym edytorze. | | `` `` | Zatwierdź | Przełącz zaznaczenie zatwierdzone/niezatwierdzone. | | `` d `` | Odrzuć | Gdy zaznaczona jest niezatwierdzona zmiana, odrzuć ją używając `git reset`. Gdy zaznaczona jest zatwierdzona zmiana, cofnij zatwierdzenie. | +| `` E `` | Edytuj fragment | Edytuj wybrany fragment w zewnętrznym edytorze. | | `` `` | Kopiuj zaznaczony tekst do schowka | | | `` , h `` | Idź do poprzedniego fragmentu | | | `` , l `` | Idź do następnego fragmentu | | @@ -220,6 +221,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` e `` | Edytuj plik | Otwórz plik w zewnętrznym edytorze. | | `` `` | Zatwierdź | Przełącz zaznaczenie zatwierdzone/niezatwierdzone. | | `` d `` | Odrzuć | Gdy zaznaczona jest niezatwierdzona zmiana, odrzuć ją używając `git reset`. Gdy zaznaczona jest zatwierdzona zmiana, cofnij zatwierdzenie. | +| `` E `` | Edytuj fragment | Edytuj wybrany fragment w zewnętrznym edytorze. | | `` `` | Kopiuj zaznaczony tekst do schowka | | | `` , h `` | Idź do poprzedniego fragmentu | | | `` , l `` | Idź do następnego fragmentu | | diff --git a/docs-master/keybindings/Keybindings_pt.md b/docs-master/keybindings/Keybindings_pt.md index 4e4f954e1..f18c1b83f 100644 --- a/docs-master/keybindings/Keybindings_pt.md +++ b/docs-master/keybindings/Keybindings_pt.md @@ -240,6 +240,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` e `` | Editar arquivo | Abrir arquivo no editor externo. | | `` `` | Etapa | Ativar/desativar seleção em staged/unstaged | | `` d `` | Descartar | Quando a mudança não desejada for selecionada, descarte a mudança usando `git reset`. Quando a mudança em fase é selecionada, despare a mudança. | +| `` E `` | Editar hunk | Editar o local selecionado no editor externo. | | `` `` | Copiar texto selecionado para área de transferência | | | `` , h `` | Ir para o local anterior | | | `` , l `` | Ir para o próximo trecho | | @@ -356,6 +357,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` e `` | Editar arquivo | Abrir arquivo no editor externo. | | `` `` | Etapa | Ativar/desativar seleção em staged/unstaged | | `` d `` | Descartar | Quando a mudança não desejada for selecionada, descarte a mudança usando `git reset`. Quando a mudança em fase é selecionada, despare a mudança. | +| `` E `` | Editar hunk | Editar o local selecionado no editor externo. | | `` `` | Copiar texto selecionado para área de transferência | | | `` , h `` | Ir para o local anterior | | | `` , l `` | Ir para o próximo trecho | | diff --git a/docs-master/keybindings/Keybindings_ru.md b/docs-master/keybindings/Keybindings_ru.md index 93b252eae..5b61abaa0 100644 --- a/docs-master/keybindings/Keybindings_ru.md +++ b/docs-master/keybindings/Keybindings_ru.md @@ -79,6 +79,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` e `` | Редактировать файл | Open file in external editor. | | `` `` | Переключить индекс | Переключить строку в проиндексированные / непроиндексированные | | `` d `` | Отменить изменение (git reset) | When unstaged change is selected, discard the change using `git reset`. When staged change is selected, unstage the change. | +| `` E `` | Изменить эту часть | Edit selected hunk in external editor. | | `` `` | Скопировать выделенный текст в буфер обмена | | | `` , h `` | Выбрать предыдущую часть | | | `` , l `` | Выбрать следующую часть | | @@ -125,6 +126,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` e `` | Редактировать файл | Open file in external editor. | | `` `` | Переключить индекс | Переключить строку в проиндексированные / непроиндексированные | | `` d `` | Отменить изменение (git reset) | When unstaged change is selected, discard the change using `git reset`. When staged change is selected, unstage the change. | +| `` E `` | Изменить эту часть | Edit selected hunk in external editor. | | `` `` | Скопировать выделенный текст в буфер обмена | | | `` , h `` | Выбрать предыдущую часть | | | `` , l `` | Выбрать следующую часть | | diff --git a/docs-master/keybindings/Keybindings_zh-CN.md b/docs-master/keybindings/Keybindings_zh-CN.md index 499651f96..831c0724a 100644 --- a/docs-master/keybindings/Keybindings_zh-CN.md +++ b/docs-master/keybindings/Keybindings_zh-CN.md @@ -291,6 +291,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` e `` | 编辑文件 | 使用外部编辑器打开文件 | | `` `` | 切换暂存状态 | 切换行暂存状态 | | `` d `` | 取消变更(git reset) | 当选择未暂存的变更时,使用git reset丢弃该变更。当选择已暂存的变更时,取消暂存该变更 | +| `` E `` | 编辑代码块 | 在外部编辑器中编辑选中的代码块 | | `` `` | 复制选中文本到剪贴板 | | | `` , h `` | 选择上一个区块 | | | `` , l `` | 选择下一个区块 | | @@ -353,6 +354,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` e `` | 编辑文件 | 使用外部编辑器打开文件 | | `` `` | 切换暂存状态 | 切换行暂存状态 | | `` d `` | 取消变更(git reset) | 当选择未暂存的变更时,使用git reset丢弃该变更。当选择已暂存的变更时,取消暂存该变更 | +| `` E `` | 编辑代码块 | 在外部编辑器中编辑选中的代码块 | | `` `` | 复制选中文本到剪贴板 | | | `` , h `` | 选择上一个区块 | | | `` , l `` | 选择下一个区块 | | diff --git a/docs-master/keybindings/Keybindings_zh-TW.md b/docs-master/keybindings/Keybindings_zh-TW.md index 8d6994350..83c46bcd4 100644 --- a/docs-master/keybindings/Keybindings_zh-TW.md +++ b/docs-master/keybindings/Keybindings_zh-TW.md @@ -80,6 +80,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` e `` | 編輯檔案 | 使用外部編輯器開啟 | | `` `` | 切換預存 | 切換現有行的狀態 (已預存/未預存) | | `` d `` | 刪除變更 (git reset) | 選取未暫存的變更時,使用 `git reset` 捨棄變更。選取已暫存的變更時,取消暫存變更。 | +| `` E `` | 編輯程式碼塊 | 在外部編輯器中編輯選中的程式碼塊。 | | `` `` | 複製所選文本至剪貼簿 | | | `` , h `` | 選擇上一段 | | | `` , l `` | 選擇下一段 | | @@ -375,6 +376,7 @@ _This file is auto-generated. To update, make the changes in the pkg/i18n direct | `` e `` | 編輯檔案 | 使用外部編輯器開啟 | | `` `` | 切換預存 | 切換現有行的狀態 (已預存/未預存) | | `` d `` | 刪除變更 (git reset) | 選取未暫存的變更時,使用 `git reset` 捨棄變更。選取已暫存的變更時,取消暫存變更。 | +| `` E `` | 編輯程式碼塊 | 在外部編輯器中編輯選中的程式碼塊。 | | `` `` | 複製所選文本至剪貼簿 | | | `` , h `` | 選擇上一段 | | | `` , l `` | 選擇下一段 | | diff --git a/pkg/gui/controllers/main_view_controller.go b/pkg/gui/controllers/main_view_controller.go index 949fae006..a4b5787ce 100644 --- a/pkg/gui/controllers/main_view_controller.go +++ b/pkg/gui/controllers/main_view_controller.go @@ -97,6 +97,14 @@ func (self *MainViewController) GetKeybindings(opts types.KeybindingsOpts) []*ty Tooltip: self.c.Tr.DiscardSelectionTooltip, DisplayOnScreen: true, }, + { + Keys: opts.GetKeys(opts.Config.Main.EditSelectHunk), + Handler: self.editHunk, + Description: self.c.Tr.EditHunk, + DescriptionFunc: self.workingTreeActionDescription(self.c.Tr.EditHunk), + GetDisabledReason: self.diffSelectionDisabledReason, + Tooltip: self.c.Tr.EditHunkTooltip, + }, { Keys: opts.GetKeys(opts.Config.Universal.CopyToClipboard), Handler: self.copySelection, @@ -396,6 +404,21 @@ func (self *MainViewController) discardSelection() error { return actions.DiscardSelection(self.context, first, last) } +// editHunk hands the hunk around the selection to an editor, and is only offered over +// the working tree's diff: what comes back is applied to the index, which is not +// something a commit's diff has any use for. +func (self *MainViewController) editHunk() error { + actions, ok := self.diffSource().(*WorkingTreeDiffActions) + if !ok { + return nil + } + first, last, ok := self.context.GetView().SelectedBufferLineRange() + if !ok { + return nil + } + return actions.EditHunk(self.context, first, last) +} + // workingTreeAction wraps a command that acts on the working tree — committing, finding // the commit to fix up — so that it only runs while the focused main view is showing the // working tree's diff. Over a commit's diff the key does nothing, so that browsing diff --git a/pkg/gui/controllers/working_tree_diff_actions.go b/pkg/gui/controllers/working_tree_diff_actions.go index 233ecec13..0dd1383da 100644 --- a/pkg/gui/controllers/working_tree_diff_actions.go +++ b/pkg/gui/controllers/working_tree_diff_actions.go @@ -3,6 +3,7 @@ package controllers import ( "fmt" "path/filepath" + "strings" "github.com/jesseduffield/generics/set" "github.com/jesseduffield/lazygit/pkg/commands/git_commands" @@ -99,6 +100,87 @@ func (self *WorkingTreeDiffActions) DiscardSelection(pane types.DiffPaneContext, }) } +// EditHunk opens the git hunk holding the selection in an editor, as a patch against +// the index, and applies whatever comes back. It is how you stage something the diff +// can't express — half of a changed line, or a change written differently from either +// side — since what the editor hands back is applied rather than matched against the +// file's own diff. +// +// The hunk is the git one, context and all, rather than lazygit's block of adjacent +// changes: an editable patch is one that still applies, and the context lines are what +// let git place it. +func (self *WorkingTreeDiffActions) EditHunk( + pane types.DiffPaneContext, firstBufferLine int, lastBufferLine int, +) error { + infos, onStagedSide, ok := self.diffLineSelection(pane, firstBufferLine, lastBufferLine) + if !ok { + return nil + } + file := self.fileForDiffLinePath(infos[0].Path) + if file == nil { + return nil + } + + parsedPatch := patch.Parse(self.c.Git().WorkingTree.WorktreeFileDiff(file, git_commands.DiffModePlain, onStagedSide)) + lineIndices := changeLineIndices(parsedPatch, infos[:1]) + if len(lineIndices) == 0 { + return nil + } + + hunkIdx := parsedPatch.HunkContainingLine(lineIndices[0]) + hunkStartIdx := parsedPatch.HunkStartIdx(hunkIdx) + patchText := parsedPatch. + Transform(patch.TransformOpts{ + Reverse: onStagedSide, + IncludedLineIndices: patch.ExpandRange(hunkStartIdx, parsedPatch.HunkEndIdx(hunkIdx)), + FileNameOverride: file.GetPath(), + }). + FormatPlain() + + patchFilepath, err := self.c.Git().Patch.SaveTemporaryPatch(patchText) + if err != nil { + return err + } + + // The patch is written with a two-line header before its hunk, so the line the + // user was on sits that much further down the file they are about to edit. + const headerLineCount = 2 + if err := self.c.Helpers().Files.EditFileAtLineAndWait(patchFilepath, + lineIndices[0]-hunkStartIdx+headerLineCount+1); err != nil { + return err + } + + editedPatchText, err := self.c.Git().File.Cat(patchFilepath) + if err != nil { + return err + } + + self.c.LogAction(self.c.Tr.Actions.ApplyPatch) + + // Everything the editor left behind is taken, this being a patch the user wrote + // rather than a selection out of one of ours. + lineCount := strings.Count(editedPatchText, "\n") + 1 + newPatchText := patch. + Parse(editedPatchText). + Transform(patch.TransformOpts{ + IncludedLineIndices: patch.ExpandRange(0, lineCount), + FileNameOverride: file.GetPath(), + }). + FormatPlain() + + if err := self.c.Git().Patch.ApplyPatch(newPatchText, git_commands.ApplyPatchOpts{ + Reverse: onStagedSide, + Cached: true, + }); err != nil { + return err + } + + // Block input until the refresh has landed, as the staging commands do: the diff is + // about to be rebuilt from a file that no longer looks the way it did. + self.c.RefreshBlockingInput(types.RefreshOptions{Scope: []types.RefreshableView{types.FILES}}) + return nil +} + // diffLineSelection resolves what the user has selected in a pane of the focused main // view to the change lines to act on, and reports whether they are the staged side of // the diff — which is a question about the pane, so it is the same for every file of a diff --git a/pkg/integration/tests/main_view/edit_hunk_in_focused_diff.go b/pkg/integration/tests/main_view/edit_hunk_in_focused_diff.go new file mode 100644 index 000000000..9b5b52347 --- /dev/null +++ b/pkg/integration/tests/main_view/edit_hunk_in_focused_diff.go @@ -0,0 +1,59 @@ +package main_view + +import ( + "github.com/jesseduffield/lazygit/pkg/config" + . "github.com/jesseduffield/lazygit/pkg/integration/components" +) + +var EditHunkInFocusedDiff = NewIntegrationTest(NewIntegrationTestArgs{ + Description: "Edit the hunk around the selection in an editor, and stage what comes back", + ExtraCmdArgs: []string{}, + Skip: false, + SetupConfig: func(cfg *config.AppConfig) { + cfg.GetUserConfig().Gui.UseHunkModeInStagingView = false + // Stand in for the editor: record the line it was pointed at, outside the + // repo so that the files panel keeps saying what the test is about, then + // write a patch that stages something neither side of the diff says. That + // is the point of editing a hunk. + cfg.GetUserConfig().OS.EditAtLineAndWait = "echo {{line}} > ../edit-line && " + + "printf '%s\\n' '--- a/file1' '+++ b/file1' '@@ -1,3 +1,3 @@' " + + "' one' '-two' '+TWO_EDITED' ' three' > {{filename}}" + }, + SetupRepo: func(shell *Shell) { + shell.CreateFileAndAdd("file1", "one\ntwo\nthree\n") + shell.Commit("one") + + shell.UpdateFile("file1", "one\nTWO\nthree\n") + }, + Run: func(t *TestDriver, keys config.KeybindingConfig) { + t.Views().Files(). + IsFocused(). + Lines( + Contains("file1").IsSelected(), + ). + Press(keys.Universal.FocusMainView) + + t.Views().Main(). + IsFocused(). + SelectedLines(Contains("-two")). + Press(keys.Main.EditSelectHunk) + + // The patch is written with a two-line header, so the deletion the cursor was + // on is its fifth line. + t.FileSystem().FileContent("../edit-line", Equals("5\n")) + + // What the editor wrote went into the index, leaving the working tree as it + // was: the file is changed on both sides now, differently. + t.Views().Files().Lines( + Contains("MM").Contains("file1"), + ) + t.Views().Secondary().ContainsLines( + Contains("-two"), + Contains("+TWO_EDITED"), + ) + t.Views().Main().ContainsLines( + Contains("-TWO_EDITED"), + Contains("+TWO"), + ) + }, +}) diff --git a/pkg/integration/tests/test_list.go b/pkg/integration/tests/test_list.go index eceaa02e6..72006a733 100644 --- a/pkg/integration/tests/test_list.go +++ b/pkg/integration/tests/test_list.go @@ -375,6 +375,7 @@ var tests = []*components.IntegrationTest{ main_view.DiscardDiffLines, main_view.DragRangeWithAutoscroll, main_view.DragSelectsDiffLineRange, + main_view.EditHunkInFocusedDiff, main_view.EditSelectedDiffLine, main_view.EscapeDismissesSelection, main_view.FileNavigationScrollsToTheTop,