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

How do I tune Vim diff so moved code blocks align more accurately?

Answer

:set diffopt+=internal,algorithm:histogram,indent-heuristic

Explanation

Default diff settings are fine for small edits, but they can produce noisy hunks when code is moved or indentation shifts. Adding histogram-based matching with indentation awareness improves alignment so related lines stay grouped, making reviews and merges faster. This is especially useful in refactors where structure changed more than raw text.

How it works

  • diffopt controls Vim's internal diff behavior
  • internal ensures Vim's built-in engine is used consistently
  • algorithm:histogram favors better matching in reordered blocks
  • indent-heuristic improves hunk boundaries around indentation changes

Together these options reduce misleading splits where logically related lines appear as delete/add churn.

Example

Without tuned diffopt, a moved function body may show as large disconnected hunks:

- old location block removed
+ new location block added

After applying:

:set diffopt+=internal,algorithm:histogram,indent-heuristic

Vim is more likely to align matching lines within those blocks, so you see focused changes instead of broad noise. That makes do/dp decisions safer during interactive merges.

Tips

  • Add this to your config if you work in diff mode often
  • For whitespace-heavy files, consider combining with iwhite
  • If a repository has unusual formatting, compare histogram and patience on a few representative diffs before standardizing

Next

How do I reselect the previous visual area and convert it to linewise selection?