Skip to content

Commit cc9085e

Browse files
committed
<leader>hv to view diff for a line blame
This keymap is useful to quickly get the full context of a particular line of code without having to leave the editor. It shows the full diff in a popover toggleterm, with the commit message at the top.
1 parent 617bf08 commit cc9085e

1 file changed

Lines changed: 30 additions & 0 deletions

File tree

lua/plugins/gitsigns.lua

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@
55
return {
66
{
77
'lewis6991/gitsigns.nvim',
8+
dependencies = {
9+
'akinsho/toggleterm.nvim',
10+
},
811
opts = {
912
on_attach = function(bufnr)
1013
local gitsigns = require 'gitsigns'
@@ -55,6 +58,33 @@ return {
5558
-- Toggles
5659
map('n', '<leader>tb', gitsigns.toggle_current_line_blame, { desc = '[T]oggle git show [b]lame line' })
5760
map('n', '<leader>tD', gitsigns.preview_hunk_inline, { desc = '[T]oggle git show [D]eleted' })
61+
62+
-- Viewing the full git diff of the blame under cursor
63+
map('n', '<leader>hv', function()
64+
local file = vim.fn.expand '%'
65+
local line = vim.fn.line '.'
66+
local blame_output = vim.fn.systemlist(string.format('git blame -L %d,+1 --porcelain -- %s', line, file))
67+
if not blame_output or #blame_output == 0 then
68+
print 'No blame info available :('
69+
return
70+
end
71+
72+
local commit = blame_output[1]:match '^(%w+)%s'
73+
if not commit then
74+
print('Could not extract commit hash from blame: ' .. blame_output[1])
75+
return
76+
end
77+
78+
local Terminal = require('toggleterm.terminal').Terminal
79+
local git_show_term = Terminal:new {
80+
cmd = 'git show ' .. commit,
81+
direction = 'float', -- or 'horizontal' / 'vertical'
82+
close_on_exit = true,
83+
hidden = true,
84+
}
85+
86+
git_show_term:toggle()
87+
end, { desc = 'git blame on current line and [v]iew diff for that SHA in toggleterm' })
5888
end,
5989
signs = { -- See `:help gitsigns` to understand what the configuration keys do
6090
add = { text = '+' },

0 commit comments

Comments
 (0)