From b07fd697e097ed0ca6040781830ad42be2a9ac86 Mon Sep 17 00:00:00 2001 From: Daanturo Date: Sun, 4 Dec 2022 21:34:52 +0700 Subject: [PATCH] * nadvice/nadvice.el: support non-symbol advices (advice-add): by aliasing the function to a new symbol --- nadvice.el | 53 +++++++++++++++++++++++++++++++---------------------- 1 file changed, 31 insertions(+), 22 deletions(-) diff --git a/nadvice.el b/nadvice.el index 58523f6..443a5d0 100644 --- a/nadvice.el +++ b/nadvice.el @@ -52,30 +52,38 @@ (defun advice-member-p (advice symbol) (ad-find-advice symbol 'around advice)) + +(defun advice--ensure-symbol (func) + (if (symbolp func) + func + (let* ((sym (intern (format "%S" func)))) + (unless (fboundp sym) + (defalias sym func)) + sym))) + ;;;###autoload (defun advice-add (symbol where function &optional props) (when props (error "This version of nadvice.el does not support PROPS")) - (unless (symbolp function) - (error "This version of nadvice.el requires FUNCTION to be a symbol")) - (let ((body (cond - ((eq where :before) - `(progn (apply #',function (ad-get-args 0)) ad-do-it)) - ((eq where :after) - `(progn ad-do-it (apply #',function (ad-get-args 0)))) - ((eq where :override) - `(setq ad-return-value (apply #',function (ad-get-args 0)))) - ((eq where :around) - `(setq ad-return-value - (apply #',function - (lambda (&rest nadvice--rest-arg) - (ad-set-args 0 nadvice--rest-arg) - ad-do-it) - (ad-get-args 0)))) - (t (error "This version of nadvice.el does not handle %S" - where))))) + (let* ((advice-fn (advice--ensure-symbol function)) + (body (cond + ((eq where :before) + `(progn (apply #',advice-fn (ad-get-args 0)) ad-do-it)) + ((eq where :after) + `(progn ad-do-it (apply #',advice-fn (ad-get-args 0)))) + ((eq where :override) + `(setq ad-return-value (apply #',advice-fn (ad-get-args 0)))) + ((eq where :around) + `(setq ad-return-value + (apply #',advice-fn + (lambda (&rest nadvice--rest-arg) + (ad-set-args 0 nadvice--rest-arg) + ad-do-it) + (ad-get-args 0)))) + (t (error "This version of nadvice.el does not handle %S" + where))))) (ad-add-advice symbol - `(,function nil t (advice lambda () ,body)) + `(,advice-fn nil t (advice lambda () ,body)) 'around nil) (ad-activate symbol))) @@ -84,9 +92,10 @@ (defun advice-remove (symbol function) ;; Just return nil if there is no advice, rather than signaling an ;; error. - (when (advice-member-p function symbol) - (ad-remove-advice symbol 'around function) - (ad-activate symbol))) + (let* ((advice-fn (advice--ensure-symbol function))) + (when (advice-member-p advice-fn symbol) + (ad-remove-advice symbol 'around advice-fn) + (ad-activate symbol)))) ) -- 2.38.1