vimtricks.wiki Concise Vim tricks, one at a time.

How do I use the patience diff algorithm in Vim to get cleaner diffs on source code?

Answer

:set diffopt+=algorithm:patience

Explanation

Vim's default diff algorithm (Myers) can produce noisy diffs when working with code — it sometimes matches unrelated lines containing common tokens like {, }, or return. The patience algorithm was designed specifically for source code: it only matches lines that are unique in both files, which tends to produce diffs that align with logical code structure.

How it works

  • :set diffopt+=algorithm:patience — enable patience diff algorithm
  • The patience algorithm avoids matching common but structurally unrelated lines (e.g., two unrelated closing braces)
  • Combine with indent-heuristic for even better results:
    set diffopt+=algorithm:patience,indent-heuristic
    
  • indent-heuristic shifts diff hunks to respect code indentation boundaries
  • Requires Vim 8.1.0360+ or Neovim 0.3.2+

Example

Refactoring a function that rearranges several blocks with shared boilerplate. Myers diff might match the braces between unrelated blocks. Patience diff correctly identifies the changed block by matching only unique lines.

:set diffopt+=algorithm:patience,indent-heuristic

Then open a diff with :diffsplit otherbranch.go to see the cleaner result.

Tips

  • Run :diffupdate to recompute the diff after changing diffopt
  • Also available: algorithm:histogram (a refinement of patience) — try both and see which suits your codebase
  • Put the setting in your vimrc / init.vim to apply it everywhere

Next

How do I open the directory containing the current file in netrw from within Vim?