Save original function, locally rebind it with fle

2019-07-12 20:57发布

问题:

subj. Something like:

(lexical-let (oldf #'original-func)
   (flet ((original-func (arg)
             do-something
             (funcall oldf arg))) 
      do-something))

don't work :(

回答1:

Hopefully this will help you with the syntax, calling swap-function calls foo1 but executes foo2.

You could write this as a useful macro with-replace-function which binds the old function with the new function while executing a body you pass in.

(defun foo1()
  (insert "hi foo1"))

(defun foo2()
  (insert "hi foo2"))

(defun swap-function(old new)
  (let ((save-func (symbol-function old)))
    (fset old (symbol-function new))
    (funcall old)
    (fset old save-func)))

(swap-function #'foo1 #'foo2)


回答2:

There is no reader macros in emacs-lisp, you need to use symbol-function explicitly.

(defun test-1 (x)
  (message "base test %s" x))

(let ((old-test-1 (symbol-function 'test-1))
      (z 10))
  (flet ((test-1 (y)
           (funcall old-test-1 y)
           (message "extended test %s" y)))
    (nic-test-1 z)))

If you want to use it as a closure you'll need to use lexical-let instead of let or set lexical-binding to T.



标签: emacs elisp