7

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.

Drew
  • 75,699
  • 9
  • 109
  • 225
Daniel Wu
  • 95
  • 2
  • 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 03 '20 at 18:50

1 Answers1

8

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.

Manuel Uberti
  • 3,150
  • 18
  • 36
  • 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 05 '20 at 02: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. – Manuel Uberti Oct 05 '20 at 05:36