feat(git): trim hunk preview header, focus float on re-invoke

This commit is contained in:
2026-05-20 06:17:56 +02:00
parent f4181b89fc
commit f77d26db6b
2 changed files with 98 additions and 17 deletions
+43 -17
View File
@@ -446,12 +446,9 @@ function M.nav(direction)
end
---@param h ow.Git.Hunks.Hunk
---@param state ow.Git.Hunks.BufState
---@return string
local function build_patch(h, state)
---@return string[]
local function hunk_body(h)
local lines = {
"--- a/" .. state.rel,
"+++ b/" .. state.rel,
string.format(
"@@ -%d,%d +%d,%d @@",
h.old_start,
@@ -466,6 +463,15 @@ local function build_patch(h, state)
for _, l in ipairs(h.new_lines) do
table.insert(lines, "+" .. l)
end
return lines
end
---@param h ow.Git.Hunks.Hunk
---@param state ow.Git.Hunks.BufState
---@return string
local function build_patch(h, state)
local lines = { "--- a/" .. state.rel, "+++ b/" .. state.rel }
vim.list_extend(lines, hunk_body(h))
return table.concat(lines, "\n") .. "\n"
end
@@ -543,16 +549,22 @@ function M.select_hunk(buf)
vim.api.nvim_win_set_cursor(0, { last, 0 })
end
local preview_win ---@type integer?
---@param buf? integer
function M.preview_hunk(buf)
local _, state, h = cursor_hunk(buf)
if preview_win and vim.api.nvim_win_is_valid(preview_win) then
vim.api.nvim_set_current_win(preview_win)
return
end
local target, state, h = cursor_hunk(buf)
if not state then
return
end
if not h then
return
end
local lines = util.split_lines(build_patch(h, state))
local lines = hunk_body(h)
local pbuf = vim.api.nvim_create_buf(false, true)
vim.api.nvim_buf_set_lines(pbuf, 0, -1, false, lines)
vim.bo[pbuf].filetype = "diff"
@@ -573,19 +585,33 @@ function M.preview_hunk(buf)
height = height,
style = "minimal",
})
vim.api.nvim_create_autocmd({ "CursorMoved", "InsertEnter", "BufLeave" }, {
once = true,
callback = function()
if vim.api.nvim_win_is_valid(win) then
vim.api.nvim_win_close(win, true)
end
end,
})
vim.keymap.set("n", "q", function()
preview_win = win
local function close()
if vim.api.nvim_win_is_valid(win) then
vim.api.nvim_win_close(win, true)
end
end, { buffer = pbuf, nowait = true })
end
local group =
vim.api.nvim_create_augroup("ow.git.hunks.preview", { clear = true })
vim.api.nvim_create_autocmd(
{ "CursorMoved", "CursorMovedI", "InsertEnter" },
{ group = group, buffer = target, callback = close }
)
vim.api.nvim_create_autocmd("WinLeave", {
group = group,
buffer = pbuf,
callback = close,
})
vim.api.nvim_create_autocmd("WinClosed", {
group = group,
pattern = tostring(win),
callback = function()
preview_win = nil
pcall(vim.api.nvim_del_augroup_by_name, "ow.git.hunks.preview")
end,
})
vim.keymap.set("n", "q", close, { buffer = pbuf, nowait = true })
end
repo.on("change", function(r, change)