Vim's diff mode is one of its best features. Or at least one of its best non-headline features. Many IDEs let you diff files, but only by leaving editorland for a specialised viewer. Vim lets you diff on the fly and carry on editing with all its usual power.
It's easy to put a buffer into diff mode - you just enter :diffthis or :diffoff. Put more than one buffer in diff mode, and off you go.
This tip takes it one step further, to set up a keymapping that toggles diffmode for a buffer, based on its current state. Add this to your .vimrc:
nnoremap <silent> <Leader>df :call DiffToggle()<CR>
function! DiffToggle()
if &diff
diffoff
else
diffthis
endif
:endfunction
Then <Leader>df will toggle diffmode for any given buffer.
This script's so simple it serves as a good way to dip a toe into writing some vimscript. Here's the same script, annotated with notes:
" Set up a keymapping from <Leader>df to a function call.
" (Note the function doesn't need to be defined beforehand.)
" Run this mapping silently. That is, when I call this mapping,
" don't bother showing "call DiffToggle()" on the command line.
nnoremap <silent> <Leader>df :call DiffToggle()<CR>
" Define a function called DiffToggle.
" The ! overwrites any existing definition by this name.
function! DiffToggle()
" Test the setting 'diff', to see if it's on or off.
" (Any :set option can be tested with &name.
" See :help expr-option.)
if &diff
diffoff
else
diffthis
endif
:endfunction