help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: replacing a function with another one


From: Florian Beck
Subject: Re: replacing a function with another one
Date: Wed, 12 Mar 2014 20:34:37 +0100
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:24.0) Gecko/20100101 Thunderbird/24.3.0


   (lambda (&rest r) (apply FUNCTION OLDFUN r))

This line tells you what the ADVICE does (in this case the around advice). But what does it mean?

1. Once you define an advice, instead of OLDFUN, emacs calls
(lambda (&rest r) (apply FUNCTION OLDFUN r)), which is a function that has any arguments and only calls (apply FUNCTION OLDFUN r)

2. &rest r means all (arbitrarily many) arguments are collected in the variable r.

3. apply then calls your FUNCTION with OLDFUN and the rest as arguments

For example, define a function:

(defun my-fun (a b)
  (list a b))

and a function we will add as an advice:

(defun my-advice (&rest args)
  args)

Add it:

(advice-add 'my-fun :around 'my-advice)

Now call (my-fun 'a 'b)

This returns ((lambda (a b) (list a b)) 1 2)

As you can see, your advice function gets called with three arguments of which the first is the original definition.

With that knowledge, we can redefine our advice function:

(defun my-advice (fun a b)
  (funcall fun a 'X))

using the first argument to call the original function.

And that is really all you have to know when advising a function

- define a new function that takes the old function as an additional first argument

 - add the advice (advice-add 'my-fun :around 'my-advice)

Things are even easier with a :before advice, where you can do anything you want with the arguments:

(defun my-fun2 (a b)
  (list a b))

(defun my-advice2 (x y)
  (message "List contains %s and %s." x y))

(advice-add 'my-fun2 :before 'my-advice2)


--
Florian Beck



reply via email to

[Prev in Thread] Current Thread [Next in Thread]