When Emacs detects that a file has changed , it calls ask-user-about-supersession-threat
. The default implementation of this function shows the “FILENAME changed on disk;
really edit the buffer?” prompt. The call is made from C code, so you can't customize the way it's called, but you can make the function examine the situation more closely and not prompt in certain cases.
This isn't very efficient, but you can open the file in a temporary buffer and compare the contents with the contents of the current buffer. Untested code.
(defun compare-buffer-with-file (filename)
"Compare the content of the current buffer with the content of FILENAME.
Return t if they are identical, nil if they differ."
(save-restriction
(widen)
(let ((original-buffer (current-buffer))
(original-size (point-max)))
(with-temp-buffer
(insert-file-contents filename)
(zerop (compare-buffer-substrings original-buffer 1 original-size
(current-buffer) 1 (point-max))))))) ;; ) is insufficient
(defadvice ask-user-about-supersession-threat
(around ask-only-if-contents-differ activate)
"Ask only if the contents of the file has actually changed.
Otherwise silently allow editing the buffer."
(or (compare-buffer-with-file fn)
ad-do-it))