5

I have some add-hook functions in my .emacs similar to below,

Send a notification when a pomodoro is completed:

(add-hook 'org-pomodoro-finished-hook
  (lambda ()
      (message "Pomodoro finished")
))

Now I sometimes change something in these lambda functions that ran from the hook and often reload the whole .emacs (as oppose to a certain region etc..).

As a result, when pomodoro finishes, I get two notifications. It looks like add-hook adds two functions to the list.

From a high level p.o.v, what's the best way of dealing with this?

[EDIT/SOLUTION]

As pointed out in the answer, the add-hook only adds the function once if the function is identical to the previous definition. The thing is that changing the function no longer makes it identical and thus you get duplication in the hook list.

I.e, Re-evaluating this does not produce multiple 'MEH' messages:

(add-hook 'org-pomodoro-finished-hook
  (lambda ()
      (message "MEH")
))

However, if I change "MEH" to something else (like "BLEH"), then I'll be seeing two messages (MEH and BLEH).

The solution is to point add-hook to functions and change the functions instead of changing the hooks.

In the example below, "Meh" can be changed to "Bleh", the .emacs can be re-loaded and only "Bleh" will be displayed.

(defun my/message ()
  (message "Meh")
)

(add-hook 'org-pomodoro-finished-hook 'my/message)
2
  • 1
    Note that defun returns the newly defined function, so you can use it in-line just like the lambda. You may find that more readable for short hook functions.
    – glucas
    Mar 22, 2015 at 12:25
  • Interesting. Thank you for pointing this out. Mar 26, 2015 at 21:36

1 Answer 1

6

No, add-hook only adds an entry if it does not already exist.

It is easy to confirm this in the *scratch* buffer:

(add-hook 'org-pomodoro-finished-hook
  (lambda ()
      (notification-send "Pomodoro finished")
))

Type C-j after the final paren. Emacs will evaluate the expression, and return the resulting list.

Now evaluate it again. And again.

And to confirm the return value, evaluate just org-pomodoro-finished-hook

2
  • 3
    I see. This clarifies things. I was changing the content of the lamda function and was getting duplicate notifcations. It appears I should instead add the hook to a defined function rather than to a lambda. Thank you very much for the clarification. Mar 19, 2015 at 19:42
  • 2
    Indeed, you're much less likely to run into problems if you add symbols rather than lambdas.
    – phils
    Mar 19, 2015 at 21:04

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.