How do I get a more accurate diff that avoids matching unrelated lines?
Answer
:set diffopt+=algorithm:histogram
Explanation
Switches Vim's diff algorithm from the default Myers algorithm to histogram, which produces more semantically meaningful diffs by avoiding false matches between boilerplate lines like braces, blank lines, or repeated identifiers.
How it works
diffopt is a comma-separated option controlling diff behavior. The algorithm: sub-option selects how lines are matched:
myers(default): fast, but prone to matching unrelated lines that happen to be identicalhistogram: builds frequency histograms of lines to find unique anchors, similar to the patience algorithm; avoids aligning common boilerplatepatience: similar to histogram but slower on large filesminimal: slowest but guaranteed to find the smallest possible diff
The histogram algorithm is the same one used by Git's --histogram option and tends to produce diffs that match programmer intent much better.
Example
When comparing two versions of a function where the body was rewritten, Myers might interleave the old and new implementations in a confusing way. Histogram aligns the function signature and closing brace as unique anchors, then shows the body as a clean replacement.
:set diffopt+=algorithm:histogram,indent-heuristic
Adding indent-heuristic further improves quality by preferring splits at lower-indented lines.
Tips
- Works in Vim 8.1+ and all Neovim versions
- Add to your config:
set diffopt+=algorithm:histogram,indent-heuristic - Run
:diffupdateto recompute after changingdiffopt - Combine with
linematch:60in Neovim for within-hunk line matching::set diffopt+=algorithm:histogram,linematch:60