Last active
November 10, 2024 13:23
-
-
Save aroben/d54d002269d9c39f0d5c89d910f7307e to your computer and use it in GitHub Desktop.
Vim script to show git commit diff in vertical split while writing commit messages
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
" Put this in your .vimrc and whenever you `git commit` you'll see the diff of your commit next to your commit message. | |
" For the most accurate diffs, use `git config --global commit.verbose true` | |
" BufRead seems more appropriate here but for some reason the final `wincmd p` doesn't work if we do that. | |
autocmd VimEnter COMMIT_EDITMSG call OpenCommitMessageDiff() | |
function OpenCommitMessageDiff() | |
" Save the contents of the z register | |
let old_z = getreg("z") | |
let old_z_type = getregtype("z") | |
try | |
call cursor(1, 0) | |
let diff_start = search("^diff --git") | |
if diff_start == 0 | |
" There's no diff in the commit message; generate our own. | |
let @z = system("git diff --cached -M -C") | |
else | |
" Yank diff from the bottom of the commit message into the z register | |
:.,$yank z | |
call cursor(1, 0) | |
endif | |
" Paste into a new buffer | |
vnew | |
normal! V"zP | |
finally | |
" Restore the z register | |
call setreg("z", old_z, old_z_type) | |
endtry | |
" Configure the buffer | |
set filetype=diff noswapfile nomodified readonly | |
silent file [Changes\ to\ be\ committed] | |
" Get back to the commit message | |
wincmd p | |
endfunction |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@dstar4138 This works great, though I found the diff dispensable if it is already included in the commit message as happens with commit.verbose > 0: