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
diffoptcontrols Vim's internal diff behaviorinternalensures Vim's built-in engine is used consistentlyalgorithm:histogramfavors better matching in reordered blocksindent-heuristicimproves 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