0

How can I detect when a diff begins and ends?

By "diff" I mean when at least 2 buffers are in diff mode (i.e. they are scroll-bound and diff syntax highlighting is visible).

I'm not asking to detect when the diff option is changed in a single buffer with autocmd OptionSet diff ... as seen in this answer Automatically disable cursorline when in diff mode?.

From this answer How to set colorscheme of vimdiff using .vimrc, I know how to detect when vim is started in diff mode via the -d option, but not when a diff begins otherwise (e.g. :diffsplit filename, :diffthis).

My goal is to change the colorscheme when a diff begins (not when only 1 buffer has diff enabled) and to reset it when the diff ends.

1 Answer 1

0

You have to count the number of buffers whose window is diff mode in the tab page. If it is more than 1, change the colorscheme. Otherwise, reset back to the original. This is a simple example:

augroup diffcolorscheme
  autocmd!
  autocmd OptionSet diff execute 'colorscheme ' . s:diffcs[1 < s:DiffBufs()]
augroup END

let s:diffcs = {'0': exists('g:colors_name') ? g:colors_name : 'default', '1': 'delek'}

function! s:DiffBufs()
  let diffbuf = []
  if expand('<amatch>') == 'diff' && v:option_old != v:option_new
    for wid in gettabinfo(tabpagenr())[0].windows
      if getwinvar(wid, '&diff')
        let bnr = winbufnr(wid)
        if index(diffbuf, bnr) == -1
          let diffbuf += [bnr]
        endif
      endif
    endfor
  endif
  return len(diffbuf)
endfunction

I have the same situation in my plugin diffchar.vim.

2
  • Why is it necessary to use the buf number instead of just whether diff is on for each window in the tabpage?
    – Steve Ward
    Dec 30, 2022 at 21:04
  • Because we can use multiple windows on one buffer, by :split command. If there are 2 or more diff mode windows on the same buffer in the tabpage, we need to count as '1' for it.
    – Rick Howe
    Dec 31, 2022 at 3:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.