Skip to content

Instantly share code, notes, and snippets.

@Konfekt
Forked from PeterRincker/diff.md
Last active October 18, 2021 08:21
Show Gist options
  • Save Konfekt/ad972d9c48b6d2fe47c8515fb73c1243 to your computer and use it in GitHub Desktop.
Save Konfekt/ad972d9c48b6d2fe47c8515fb73c1243 to your computer and use it in GitHub Desktop.
:DiffOrig but smarter

:DiffOrig but smarter

This is an enhanced version of the snippet provided under :help diff-original-file.

Where the original :DiffOrig only shows differences between the buffer in memory and the file on disk, :Diff can be used in two ways:

  • against the file on disk, like the original, with:

    :Diff
    
  • against an arbitrary Git revision of the current file, with:

    :Diff HEAD
    

Adapted from here by checking for git dir and executable.

function! Diff(mods, spec) abort
let mods = a:mods
if !len(mods) && &diffopt =~# 'vertical'
let mods = 'vertical'
endif
let cmd = '++edit #'
if len(a:spec)
let gitdir = finddir('.git', '.;')
if empty(gitdir)
echoerr 'no git dir found!'
return 1
else
if !executable('git')
echoerr 'no git executable found!'
return 1
else
let cmd = "!git -C " . shellescape(fnamemodify(gitdir, ':p:h:h')) . " show " . a:spec . ":#"
endif
endif
endif
execute mods . ' new'
setlocal bufhidden=wipe buftype=nofile nobuflisted noswapfile
execute "read " . cmd
silent 0d_
let &filetype = getbufvar('#', '&filetype')
augroup Diff
autocmd! * <buffer>
autocmd BufWipeout <buffer> diffoff!
augroup END
diffthis
wincmd p
diffthis
endfunction
command! -nargs=? Diff call Diff(<q-mods>, <q-args>)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment