In my old emacs, I have defined the following code.

   (add-hook 'focus-out-hook (lambda () (save-some-buffers t)))

After upgrade to emacs 27, it said focus-out-hook is obsoleted, and the new one is after-focus-change-function, but simply replace it doesn't work. The following doesn't work

(add-hook 'after-focus-change-function (lambda () (save-some-buffers t)))

Looks to me the first is a hook, so need to use add-hook, but for the new function to work, how to use it? My purpose is to save a buffer after I switch to another app.

  • Too bad that the message saying to use the new instead of the old doesn't tell you how to do that, if the new doesn't just replace the old with no other code changes needed. IMO, this is a failing of Emacs. Maybe M-x report-emacs-bug?
    – Drew
    Oct 3, 2020 at 18:50

1 Answer 1


You could try using something like:

(add-function :after after-focus-change-function #'your-function-here)

So, in your case, something like this should do what you are after:

(add-function :after after-focus-change-function (lambda () (save-some-buffers t)))

If you look at the documentation of after-focus-change-function with C-h v after-focus-change-function RET, you will notice that it suggests to use add-function to modify it:

[...] Code wanting to do something when frame focus changes should use add-function to add a function to this one [...]

Note also that the documentation suggests that your function should call frame-focus-state to retrieve the last known focus state of each frame, so you could do something like:

(add-function :after after-focus-change-function (lambda () (unless (frame-focus-state) (save-some-buffers t))))

Note that frame-focus-state returns nil when the selected frame is not focused.

  • There is some slight difference: for focus-out-hook, when I move my mouse out of emacs and on a new app (when using the touch pad of mac), even if I didn't click mouse on the app, it will save the buffer. But when using the new function, only when I click mouse on the new app, will emacs save buffer.
    – Daniel Wu
    Oct 5, 2020 at 2:17
  • Sorry, the answer I provided is as far as my knowledge about after-focus-change-function go. You could M-x report-emacs-bug to ask for more detailed documentation about its usage. Oct 5, 2020 at 5:36

Your Answer

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

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