5

Is there any way to get emacs to actually check the contents of files on disk when determining this?

E.g. if I have some unsaved changes to a file, and temporarily switch source control branches (to make changes to other files), then switch back again, I want to be able to continue editing where I left off without this prompt. (the prompt would be much more trustworthy and useful if it only warned me when the file had really changed)

I think it currently goes by timestamp or something.

EoghanM
  • 205
  • 1
  • 4
  • Most files I work with don't get updated without data being modified. I guess it's the same for you, so it might be a good idea to enable `auto-revert-mode` for those very specific files. – YoungFrog Mar 21 '16 at 16:38
  • Could you clarify your question? Emacs uses file modifcation times. Is the problem that some process is changing the modification time (but not the file contents)? – scbagley Mar 21 '16 at 20:21
  • @scbagley Yes: some process changes the file to an identical version (or perhaps even to a different version, then back to the original). Emacs only sees that the timestamp has changed, it doesn't know that the content is the same. – Gilles 'SO- stop being evil' Mar 21 '16 at 21:47

1 Answers1

3

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)))))))
(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))
  • Thanks Gilles, this doesn't work for me (I still get the prompt), but it's likely the right direction to go in. – EoghanM Mar 27 '16 at 10:29