Given two buffers, how do I find the first character position where their contents differ? E.g. for contents abcdef and abcDeF, the first difference would be at point=4. For abc and ab, it would be at point=3.

Is there anything more direct than writing my own binary search based on compare-buffer-substrings to compare progressively smaller substrings?

1 Answer 1


Why a binary search? compare-buffer-substrings returns the number of chars that were equal. So you can just do:

(goto-char (+ (point-min) -1
              (abs (compare-buffer-substrings
                    BUF1 nil nil BUF2 nil nil))))

you may want to let-bind case-fold-search around the call to specify if you prefer to be case-sensitive or case-insensitive, of course.

  • lol, sure enough the function's documentation says "if first string is less after N-1 chars". Somehow I managed to miss the after N-1 chars part and got the impression that the return value worked like strcmp in C. Should I just delete my question?
    – Lassi
    Commented Mar 29, 2018 at 12:55

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.