1

I want to do something like if the "buffer-changed" but "content-not-changed", reverted the buffer.

When I work on the checking if the content changed, I tested the following code, but it can't work, it always return nil even if I just save the buffer.

(defun file-content-keep-same(BUFFER)
  (interactive)
  (save-restriction 
  (widen)
  (let ((original-buffer BUFFER)
    (original-size (buffer-size BUFFER))
    (filename-on-disk (buffer-file-name (current-buffer))))
    (message "buffer size %d" original-size)
    (with-temp-buffer
      (insert-file-contents filename-on-disk)
      (message "%s %d" filename-on-disk (point-max))
      (zerop
       (compare-buffer-substrings original-buffer 1 original-size
                 (current-buffer) 1 (point-max))))
    )
  ))

where is it wrong for above code?

3

where is it wrong for above code?

(buffer-size)(point-max), your use of compare-buffer-substrings is incorrect. A better idea is omitting the START1/END1/START2/END2 argument by supplying nil, then (point-min) and (point-max) will be used automatically in corresponding buffers.


Here is my attempt (for code simplicity, it doesn't take account of narrowing)

(defun same-buffer-file-p (buffer file)
  "Return t if BUFFER and FILE have the same contents."
  (with-temp-buffer
    (insert-file-contents file)
    (zerop
     (let ((case-fold-search nil))
       (compare-buffer-substrings buffer nil nil
                                  (current-buffer) nil nil)))))

;;; Tests

(write-region "hello" nil "hello.txt")

(with-temp-buffer
  (insert "hello")
  (same-buffer-file-p (current-buffer) "hello.txt"))
;; => t

(with-temp-buffer
  (insert "HELLO")
  (same-buffer-file-p (current-buffer) "hello.txt"))
;; => nil

By the way, Emacs already provides similar feature in C-x s (save-some-buffers) then d (or simply M-x diff-buffer-with-file).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.