Nathaniel Flath
Nathaniel Flath

Reputation: 16025

Save value of old function in elisp to call

I have a function:

(defun alternate-narrow-to-region (start end)
   (message "Hi!")
   (narrow-to-region start end))

I want all uses of narrow-to-region, except for the one in this function body, to call alternate-narrow-to-region (so narrow-to-defun, narrow-to-page, direct calls to narrow-to-region, end up calling alternate-narrow-to-region).

How do I do this?

Upvotes: 1

Views: 200

Answers (1)

Drew
Drew

Reputation: 30708

  1. To save the original definition (which is in your question title but not in the text), use defalias:

    (defalias 'ORIGINAL-narrow-to-region (symbol-function 'narrow-to-region) "My doc string about this.")

    Note that in this case you do not want to use this:

    (defalias 'FOREVER-narrow-to-region 'narrow-to-region "My doc string about this.")

    What you want to do is copy the function definition at a given point in time. The latter use of defalias instead has the effect of pointing FOREVER-narrow-to-region to whatever the current definition of narrow-to-region is. If you redefine narrow-to-region then it will point to the new definition, which is presumably not what you want in this case.

  2. As for the question implied by your text, the answer is that you cannot. You cannot get Emacs to always use your function instead of narrow-to-region. This is explained at your other question: code that calls narrow-to-region and is compiled will continue to (in effect) call the original narrow-to-region. (It is not really called at all. Its code is effectively inlined.)

  3. If you wanted to get Emacs to use a replacement command only when called interactively, you could of course remap the original command's key bindings to the replacment. But that does not seem to be the case here.

Upvotes: 1

Related Questions