Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emacs: define custom hook on a command

Tags:

emacs

hook

Is there a way to hook onto command A, so that B is always called after A executes?

like image 543
Trong Truong Avatar asked Feb 28 '26 11:02

Trong Truong


2 Answers

I think the most straight-forward way to accomplish this is through the use of advice. You would do something along the lines of:

(defadvice command-A (after b-after-a activate)
  "Call command-B after command-A"
  (command-B))

This approach has the advantage that it works even when command-A is redefined. It does not, however, work on macros or on primitive functions called from the C code. But, in practice the thought of advising those functions is rare.

That said, it might be worth looking into just defining a new command (command-C) which first calls command-A and then command-B.

You could also play around with symbol function indirection and writing a new command.

It kind of depends on what you're trying to solve.

like image 185
Trey Jackson Avatar answered Mar 02 '26 15:03

Trey Jackson


You can advice a function using defadvice:

;; This is the original function command-A
(defun command-A () (do-it))

;; This call will cause (do-sometihng-after-command-A) to be called 
;; every-time (command-A) is called.
(defadvice command-A (after after-command-A)
    (do-something-after-command-A))

;; Enable the advice defined above
(ad-activate 'command-A)

See the info node (elisp)Advising Functions for more information and examples.

like image 34
Burton Samograd Avatar answered Mar 02 '26 15:03

Burton Samograd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!