-- The file beside its committed version, as a two-window diff. local M = {} function M.diff_head() local file = vim.api.nvim_buf_get_name(0) if file == "" or vim.bo.buftype ~= "" then return vim.notify("Diff: this buffer is not a file", vim.log.levels.INFO) end if vim.fn.executable("git") == 0 then return vim.notify("Diff: git is not installed", vim.log.levels.WARN) end local dir = vim.fn.fnamemodify(file, ":h") local rel = vim.fn.systemlist({ "git", "-C", dir, "ls-files", "--full-name", "--", file })[1] if vim.v.shell_error ~= 0 or not rel or rel == "" then return vim.notify("Diff: this file is not tracked by git", vim.log.levels.INFO) end local old = vim.fn.systemlist({ "git", "-C", dir, "show", "HEAD:" .. rel }) if vim.v.shell_error ~= 0 then return vim.notify("Diff: no committed version of this file yet", vim.log.levels.INFO) end local ft, win = vim.bo.filetype, vim.api.nvim_get_current_win() vim.cmd("leftabove vnew") local buf = vim.api.nvim_get_current_buf() vim.api.nvim_buf_set_lines(buf, 0, -1, false, old) vim.bo[buf].buftype = "nofile" vim.bo[buf].bufhidden = "wipe" vim.bo[buf].swapfile = false vim.bo[buf].modifiable = false vim.bo[buf].filetype = ft pcall(vim.api.nvim_buf_set_name, buf, "HEAD:" .. rel) vim.cmd.diffthis() vim.api.nvim_set_current_win(win) vim.cmd.diffthis() local function close() if vim.api.nvim_buf_is_valid(buf) then vim.api.nvim_buf_delete(buf, { force = true }) end if vim.api.nvim_win_is_valid(win) then vim.api.nvim_win_call(win, function() vim.cmd.diffoff() end) end end vim.keymap.set("n", "q", close, { buffer = buf, nowait = true, desc = "Close the diff" }) end local function hunk_at_cursor(action) local ok, diff = pcall(require, "mini.diff") if not ok then return end local line = vim.api.nvim_win_get_cursor(0)[1] pcall(diff.do_hunks, 0, action, { line_start = line, line_end = line }) end function M.stage_hunk() hunk_at_cursor("apply") end function M.reset_hunk() hunk_at_cursor("reset") end return M