6
votes

Emacs says,

Buffer foo.txt has shrunk a lot; auto save disabled in that buffer until next real save

when it detects that a lot of text is gone upon auto save time, and disables auto save, unless auto-save-include-big-deletions is non-nil.

How can I hook into this event of Emacs detecting that the buffer has shrunk a lot? I want to hook into that because I want to set a buffer-local flag whenever buffer gets shrunk a lot so that when I do save-some-buffers, one of its advices would detect the flag and say to me "hey, this buffer has shrunk a lot. don't forget to see diff to make sure you didn't delete some big chunk by mistake". This would be nice in addition to backups. Simply comparing the size of buffer before save and the saved file would fail to detect the case of adding a lot then deleting a lot by mistake then saving.

1
That logic seems to be implemented in C code... maybe hooking into it won't be easy. Have you considered using a 'find-file-hook' to set the initial file size (- (point-max) (point-min)) and comparing current size with that value when doing 'save-some-buffers'? - juanleon
Using find-file-hook, one cannot detect cases of a user adding a lot of new text then deleting a lot of old text by mistake then saving (all within Emacs) - Jisang Yoo

1 Answers

4
votes

The auto-save-hook gets run before the check that generates that message, so you can replicate the logic in the C code to do what you want. So you can add a function to that hook.

This is (AFAIK) the logic that is used in the C code.

(when (and auto-save-include-big-deletions
           buffer-file-name
           (> (* 10 (nth 7 (file-attributes buffer-file-name)))
              (* 13 (buffer-size)))
           (> (nth 7 (file-attributes buffer-file-name)) 5000))
  ;; do something
  )

Note: it looks like the hook gets run even when the auto-save has been disabled.