0

I want to tell Emacs to never auto-save files bigger than ~1MB. I know how to turn off auto-save-mode when the file size is above a certain limit, but not how to make that function run automatically in every buffer. I don't want to add a mode hook for every major mode.

This was my naive attempt to use auto-save-mode-hook to solve the problem:

(add-hook 'auto-save-mode-hook
          (lambda ()
            (if (buffer-file-name)
                (if (> (file-attribute-size
                        (file-attributes
                         (buffer-file-name)))
                       1000000)
                    (auto-save-mode 0))
              (auto-save-mode 0))))

I get an error about excessively deep nesting; presumably, running (auto-save-mode 0) is executing auto-save-mode-hook again. I'm not quite sure why this would happen, given that it is turning off the mode, not turning it on, but clearly this approach is not going to work as I wrote it. Does anyone have either an alternate strategy or a fix to mine?

1 Answer 1

3

presumably, running (auto-save-mode 0) is executing auto-save-mode-hook again. I'm not quite sure why this would happen, given that it is turning off the mode, not turning it on,

C-h f auto-save-mode: "... The mode’s hook is called both when the mode is enabled and when it is disabled. ..."

So your code will run again and again.


You may need to check whether the mode is on before toggling it.

Just draft:

(add-hook 'auto-save-mode-hook
          #'(lambda ()
              (when (and buffer-auto-save-file-name
                         (>= buffer-saved-size 0))
                ;; OK, auto-save-mode is enabled.
                ;; Maybe you want to disable it.
                (when (Do_you_want_to_turn_off_it?)
                  (auto-save-mode -1)))))
2
  • Why do we check whether buffer-saved-size is greater than or equal to zero? Is it not sufficient to check buffer-auto-save-file-name?
    – Zorgoth
    Feb 17 at 10:58
  • 1
    @Zorgoth: buffer-saved-size may be negative so that auto-saving won’t happen temporarily but actually it is on. The statements about auto-save-mode in the help doc are a little vague IMHO because the doc says “To check whether the minor mode is enabled in the current buffer, evaluate ‘(and buffer-auto-save-file-name (>= buffer-saved-size 0))’.” But in my trials, auto-save-mode-hook is NOT called after evaluating (setq buffer-saved-size -1). Checking only buffer-auto-save-file-name will be fine in your case :-)
    – shynur
    Feb 17 at 13:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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